Share via


How to: Draw Text on a Form

This example demonstrates how to draw text on a form.

Example

private 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;
    formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);
    drawFont.Dispose();
    drawBrush.Dispose();
    formGraphics.Dispose();
}

Compiling the Code

This example requires:

  • A Windows Forms Application project.

  • Call the DrawString() method from an event handler. For example, you can add a Button to the form, and call DrawString from the click event handler for the button.

Robust Programming

You should always call Dispose on any objects that consume system resources, such as Font and Graphics objects.

The following condition may cause an exception:

  • The Arial font is not installed.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

Drawing Text and Graphics

Visual C# Guided Tour