How to: Draw Text on a Form (Visual C#) 

This example demonstrates drawing 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 Application project.

The code needs to be within the scope of the form class. The instance of the form is represented by this.

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

Other Resources

Visual C# Express
C# Programming Examples