Paul Mehner

blog

  Home  |   Contact  |   Syndication    |   Login
  37 Posts | 0 Stories | 29 Comments | 15 Trackbacks

News

Archives

Post Categories

Old 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);

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Friday, April 28, 2006 4:44 PM

Feedback

# re: Calculating Size of Multi-Line WinForm Label With MeasureText 6/25/2008 6:59 AM Jan Moeller
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


# re: Calculating Size of Multi-Line WinForm Label With MeasureText 4/23/2010 3:18 AM Geoff Tyrer
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);

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: