How to determine the size of the string based on the font

I have a small form that displays some progress information.
Very rarely do I have to show a rather long message, and I want to be able to resize this form if necessary so that this message matches the form.

So, how do I know how wide line S will be displayed in font F ?

+15
c # fonts winforms
Apr 6 '09 at 12:14
source share
3 answers

It depends on the rendering engine used. You can switch between GDI and GDI +. Switching can be done by setting the UseCompatibleTextRendering property UseCompatibleTextRendering respectively

When using GDI +, you should use MeasureString :

 string s = "A sample string"; SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24)); 

When using GDI (i.e. native Win32 rendering) you should use the TextRenderer class:

 SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24)); 

See article: Text rendering: building world-based applications using complex scripts in Windows Forms controls

+17
Apr 6 '09 at 12:22
source share

How about this:

 Size stringsize = graphics.MeasureString("hello", myFont); 

( Here is the MSDN link.)

+5
Apr 6 '09 at 12:18
source share

In Win32, I used the equivalent for the VisualStyleRenderer :: GetTextExtent function for this.

0
Apr 6 '09 at 12:18
source share



All Articles