tags:

views:

3372

answers:

5

A Java version of this question was just answered, and, well, I don't know how to do this in .net.

So how do you calculate the display width of a string in C# / .net?

+10  A: 

You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.

For WinForms: Graphics.MeasureString

For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...

Jon Skeet
In WPF you would use FormattedText, http://msdn.microsoft.com/en-us/library/system.windows.media.formattedtext.aspx.
Todd White
@Todd: Thanks :)
Jon Skeet
+6  A: 

Graphics.MeasureString but its a bit crappy, as is explained and improved upon; here

Andrew Bullock
+2  A: 

You would use Graphics.MeasureString.

http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

jons911
+8  A: 

An alternative for Windows Forms is the static TextRenderer.MeasureText method.

Although restricted to integer sizes, this (in tandem with TextRenderer.DrawText) renders more accurate and much higher quality ClearType text than the Graphics.MeasureString/DrawString duo.

Alan
Cool. Never heard of the TextRenderer before.
MusiGenesis
+8  A: 

In WPF you would use FormattedText.

Todd White