Search code examples
c#wpfstringformatted-text

How to get width of a string in plain c#


I have an application where we replace place holding text with other text at run time. While doing so I have to add character ellipses if the string goes beyond some predefined width.

So I do not have a DrawingContext available nor i have a Graphics.Measure available.

I used FormattedText but I was unable to extract the ellipted text. I could never find the right way to use a formatted text like this. Please help.


Solution

  • For WinForms, you can use the TextRenderer.MeasureText function,

    and thanks to the comment from vcjones, using the method described at http://smellegantcode.wordpress.com/2008/07/03/glyphrun-and-so-forth/ for WPF.