Porady: rysowanie tekstu w formularzu systemu Windows

Poniższy przykład kodu pokazuje, jak użyć DrawString metody , Graphics aby rysować tekst w formularzu. Alternatywnie można użyć funkcji TextRenderer do rysowania tekstu w formularzu. Aby uzyskać więcej informacji, zobacz How to: Draw Text with GDI (Instrukcje: rysowanie tekstu za pomocą interfejsu GDI).

Przykład

public:
    void DrawString()
    {
        System::Drawing::Graphics^ formGraphics = this->CreateGraphics();
        String^ drawString = "Sample Text";
        System::Drawing::Font^ drawFont =
            gcnew System::Drawing::Font("Arial", 16);
        System::Drawing::SolidBrush^ drawBrush = gcnew
            System::Drawing::SolidBrush(System::Drawing::Color::Black);
        float x = 150.0F;
        float y = 50.0F;
        System::Drawing::StringFormat^ drawFormat =
            gcnew System::Drawing::StringFormat();
        formGraphics->DrawString(drawString, drawFont, drawBrush, x,
            y, drawFormat);
        delete drawFont;
        delete drawBrush;
        delete formGraphics;
    }

public void DrawString()
{
    System.Drawing.Graphics formGraphics = this.CreateGraphics();
    string drawString = "Sample Text";
    System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16);
    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
    float x = 150.0F;
    float y = 50.0F;
    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
    formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
    drawFont.Dispose();
    drawBrush.Dispose();
    formGraphics.Dispose();
}

Public Sub DrawString()
    Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
    Dim drawString As String = "Sample Text"
    Dim drawFont As New System.Drawing.Font("Arial", 16)
    Dim drawBrush As New _
       System.Drawing.SolidBrush(System.Drawing.Color.Black)
    Dim x As Single = 150.0
    Dim y As Single = 50.0
    Dim drawFormat As New System.Drawing.StringFormat
    formGraphics.DrawString(drawString, drawFont, drawBrush, _
        x, y, drawFormat)
    drawFont.Dispose()
    drawBrush.Dispose()
    formGraphics.Dispose()
End Sub

Kompilowanie kodu

Nie można wywołać DrawString metody w procedurze obsługi zdarzeń Load . Narysowana zawartość nie zostanie ponownie wyrysowana, jeśli rozmiar formularza zostanie zmieniony lub zasłonięty przez inny formularz. Aby zawartość automatycznie przemalować, należy zastąpić metodę OnPaint .

Niezawodne programowanie

Następujące warunki mogą spowodować wyjątek:

  • Czcionka Arial nie jest zainstalowana.

Zobacz też