How can I tell when the Text of a System.Windows.Forms.GroupBox wraps to the next line?

Posted by fre0n on Stack Overflow See other posts from Stack Overflow or by fre0n
Published on 2010-03-12T19:54:00Z Indexed on 2010/03/12 19:57 UTC
Read the original article Hit count: 192

Filed under:
|
|
|

I'm creating a GroupBox at runtime and setting its Text property. Usually, the text is only on one line, but sometimes it wraps. The problem is that the controls contained in the GroupBox cover up the GroupBox's text.

What I'd like to do is determine if and when the text wraps. Specifically, I'd like to determine how much extra height the wrapped text takes up as compared to a single line. That way, I can reposition the GroupBox's controls and adjust its height.

Initially, I thought I'd do this by calling the GroupBox's CreateGraphics() method, and using the Graphics to measure the string. Something like this:

private void SetGroupBoxText(GroupBox grp, string text)
{
    const int somePadding = 10;

    Graphics g = grp.CreateGraphics();
    SizeF textSize = g.MeasureString(text, grp.Font);
    if (textSize.Width > (grp.Width - somePadding))
    {
        // Adjust height, etc.
    }
}

The problem is that the size generated by g.MeasureString(text, grp.Font) doesn't seem to be accurate. I determined that it wasn't accurate by putting enough of a single character to cause a wrap, then measuring the resulting string.

For example, it took 86 pipes (|) to until a wrap happened. When I measured that string, its width was ~253. And it took 16 capital W's to force a wrap - its string had a width of ~164. These were the two extremes that I tested. My GroupBox's width was 189. (a's took 29 and had a width of ~180, O's took 22 and had a width of ~189)

Does anyone have any ideas? (hacks, WinAPI, etc. are welcome solutions)

© Stack Overflow or respective owner

Related posts about .NET

Related posts about winforms