Monday, March 06, 2006

New text rendering in .NET 2.0 WinForms

Winforms 2.0 added support for drawing GDI text with the new TextRenderer class available in the Systems.Windows.Forms namespace. Using this class to draw strings is now the preferred way instead of using the previous Graphics.DrawString method. So not to break previous WinForms applications, there is a new property on controls called UseCompatibleTextRendering, and if set to True this will draw text as it used to in 1.1.

On application startup, you can globally set this on all controls with:
This draws all the labels in the system much clearer than previous versions especially when using the Tahoma 8.25pt font. When using this font at design time and dragging fields from your datasources window, the labels will line up using the new 2.0 behavior, but if you forget to set this at runtime using the above code, you may notice your labels not lining up properly.

If drawing strings manually, like from paint handlers on controls, you'll want to use the new TextRenderer.

So instead of:
Graphics.DrawString(someText, Me.Font, New SolidBrush(Me.ForeColor), rect)
Use this code instead:
TextRenderer.DrawText(Graphics, someText, Me.Font, rect, Me.ForeColor, TextFormatFlags.Left)

1 comment:

Rakesh Kumawat said...

This is usefull information..