How to: Draw Text on a Windows Form
The following code example shows how to use the DrawString method of the Graphics to draw text on a form. Alternatively, you can use TextRenderer for drawing text on a form. For more information, see How to: Draw Text with GDI.
Example
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
Compiling the Code
You cannot call the DrawString method in the Load event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the OnPaint method.
Robust Programming
The following conditions may cause an exception:
- The Arial font is not installed.
See also
Samarbeta med oss på GitHub
Källan för det här innehållet finns på GitHub, där du även kan skapa och granska ärenden och pull-begäranden. Se vår deltagarguide för mer information.
.NET Desktop feedback