Como: Desenhar texto em um formulário do Windows

O exemplo de código a seguir mostra como usar o DrawString método para o Graphics Para desenhar texto em um formulário. Como alternativa, você pode usar TextRenderer Para desenhar texto em um formulário. Para obter mais informações, consulte Como: Desenhar texto com GDI.

Exemplo

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

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:
    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;
    }

Compilando o código

Não é possível chamar o DrawString método na Load manipulador de eventos. O conteúdo desenhado não irá ser redesenhado se o formulário for redimensionado ou obscurecido por outro formulário.Para tornar seu conteúdo automaticamente redesenhado, você deve substituir o OnPaint método.

Programação robusta

As seguintes condições podem causar uma exceção:

  • A fonte Arial não está instalada.

Consulte também

Tarefas

Como: Desenhar texto com GDI

Referência

DrawString

DrawText

FormatFlags

StringFormatFlags

TextFormatFlags

OnPaint

Outros recursos

Noções básicas sobre programação de gráficos