How to: Draw Text with GDI
With the DrawText method in the TextRenderer class, you can access GDI functionality for drawing text on a form or control. GDI text rendering typically offers better performance and more accurate text measuring than GDI+.
Note
The DrawText methods of the TextRenderer class are not supported for printing. When printing, always use the DrawString methods of the Graphics class.
Example
The following code example demonstrates how to draw text on multiple lines within a rectangle using the DrawText method.
Private Sub RenderText6(ByVal e As PaintEventArgs)
Dim flags As TextFormatFlags = TextFormatFlags.Bottom Or _
TextFormatFlags.EndEllipsis
TextRenderer.DrawText(e.Graphics, _
"This is some text that will be clipped at the end.", _
Me.Font, New Rectangle(10, 10, 100, 50), SystemColors.ControlText, flags)
End Sub
private void RenderText6(PaintEventArgs e)
{
TextFormatFlags flags = TextFormatFlags.Bottom | TextFormatFlags.EndEllipsis;
TextRenderer.DrawText(e.Graphics, "This is some text that will be clipped at the end.", this.Font,
new Rectangle(10, 10, 100, 50), SystemColors.ControlText, flags);
}
To render text with the TextRenderer class, you need an IDeviceContext, such as a Graphics and a Font, a location to draw the text, and the color in which it should be drawn. Optionally, you can specify the text formatting by using the TextFormatFlags enumeration.
For more information about obtaining a Graphics, see How to: Create Graphics Objects for Drawing. For more information about constructing a Font, see How to: Construct Font Families and Fonts.
Compiling the Code
The preceding code example is designed for use with Windows Forms, and it requires the PaintEventArgs e, which is a parameter of PaintEventHandler.