MeasureString for wrapped multi-line text height in .NET Compact Framework

Monday, April 7th, 2008

In .NET Compact Framework, Graphics.MeasureString only measures the required width and height for a single line string.  What happens if the text is wrapped?

Several years ago, I used this piece of code to measure a wrapped string height.  Not pretty, but works.  A couple of days ago, I found this code, which utilizes the DrawText API, I think is better, but I did not like the idea of taking a control as input.  Combine these two, I have this code:

static public Size MeasureStringEx(Graphics gr, string text, Font font, Rectangle rect)
{
    RECT bounds = new RECT();
    bounds.left = rect.Left;
    bounds.right = rect.Right;
    bounds.bottom = rect.Bottom;
    bounds.right = rect.Right;

    IntPtr hFont = font.ToHfont();
    IntPtr hdc = gr.GetHdc();
    IntPtr originalObject = CoreDll.SelectObject(hdc, hFont);
    int flags = CoreDll.DT_CALCRECT | CoreDll.DT_WORDBREAK;
    CoreDll.DrawText(hdc, text, text.Length, ref bounds, flags);
    CoreDll.SelectObject(hdc, originalObject);
    gr.ReleaseHdc(hdc);
    return new Size(bounds.right - bounds.left, bounds.bottom - bounds.top);
}

and the CoreDll API imports:

Public struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

[DllImport("coredll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);

[DllImport("coredll.dll")] public static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref RECT lpRect, int wFormat);
public static int DT_CALCRECT = 0x00000400;
public static int DT_WORDBREAK = 0x00000010;

This entry is filed under .NETCF, Mobile. You can follow any responses to this entry through the RSS 2.0 feed.You can leave a response, or trackback from your own site.

No Comments to “MeasureString for wrapped multi-line text height in .NET Compact Framework”

Leave a Reply

You must be logged in to post a comment.