Compartilhar via


Como: Desenhar texto em um Windows Form

O exemplo de código a seguir mostra como usar o DrawString método o Graphics para desenhar o 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

Você não pode chamar o DrawString método de Load manipulador de eventos. O conteúdo desenhado não irá ser redesenhado, se o formulário é redimensionado ou obscurecido por um 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

Introdução à programação de gráficos