Geeks With Blogs
Paul Mehner blog

In older .net framework versions, calculating the height of a multi-line windows form label was not a straightforward task. I recently tripped acrossed a new technique available in the 2.0 framework for calculating the space that a label will occupy given its font and the runtime screen resolution, making this task easy.

using System.Windows.Forms
TextRenderer.MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags);

Sample Use:

Label lbC;
TextRenderer.MeasureText((IDeviceContext)lbC.CreateGraphics(), lbC.Text, lbC.Font, lbC.Size, TextFormatFlags.WordBreak);

 

Posted on Friday, April 28, 2006 4:44 PM | Back to top


Comments on this post: Calculating Size of Multi-Line WinForm Label With MeasureText

# re: Calculating Size of Multi-Line WinForm Label With MeasureText
Requesting Gravatar...
Thanks for TextRenderer sample
It works even better if you use lbC.ClientSize instead of lbC.Size, as the label uses a few pixels for border and margin.
- Jan
Left by Jan Moeller on Jun 25, 2008 6:59 AM

# re: Calculating Size of Multi-Line WinForm Label With MeasureText
Requesting Gravatar...
TextRenderer.MeasureText does not seem to handle sequences of characters (e.g. long path/filename) that are longer than the width of the label - it returns the width required for longest such "word" and does not break it into two as the actual label will.

What I had to do was (a) Split the text "lines" (b) Measure the height of each "line" (c) Set label height to the total line height.

Here is some sample code:
// Split message into lines
char[] aSep = { '\r' };
string sInput = sMessage.Replace("\r\n", "\r");
string[] asInput = sInput.Split(aSep);

// Determine the height of a line so we can handle empty lines and split lines
Graphics graphics = lbl_Message.CreateGraphics();
Size sizeLineHeight = TextRenderer.MeasureText(
(IDeviceContext)lbl_Message.CreateGraphics(),
"A",
lbl_Message.Font,
lbl_Message.Size,
TextFormatFlags.WordBreak);
int nLineHeight = sizeLineHeight.Height;

// Calculate total height of all input lines
int nTotalHeight = 0;
foreach (string sInputLine in asInput)
{
if (string.IsNullOrEmpty(sInputLine))
{
nTotalHeight += nLineHeight;
}
else
{
Size sizeTemp = TextRenderer.MeasureText(
(IDeviceContext)lbl_Message.CreateGraphics(),
sInputLine,
lbl_Message.Font,
lbl_Message.Size,
TextFormatFlags.WordBreak);
if (sizeTemp.Width > lbl_Message.Width)
{
// We are dealing with a "word" that is wider than the label
int nLines = (sizeTemp.Width / lbl_Message.Width) + 1;
nTotalHeight += (nLines * nLineHeight);
}
else
{
nTotalHeight += sizeTemp.Height;
}
}
}
lbl_Message.Size = new Size(lbl_Message.Width, nTotalHeight);
Left by Geoff Tyrer on Apr 23, 2010 3:18 AM

Your comment:
 (will show your gravatar)


Copyright © Paul Mehner | Powered by: GeeksWithBlogs.net