MeasureString for wrapped multi-line text height in .NET Compact Framework
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) IntPtr hFont = font.ToHfont();
{
RECT bounds = new RECT();
bounds.left = rect.Left;
bounds.right = rect.Right;
bounds.bottom = rect.Bottom;
bounds.right = rect.Right;
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 [DllImport("coredll")] [DllImport("coredll.dll")] public static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref RECT lpRect, int wFormat);
{
public int left;
public int top;
public int right;
public int bottom;
}
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
public static int DT_CALCRECT = 0x00000400;
public static int DT_WORDBREAK = 0x00000010;
Posted in .NETCF, Mobile | No Comments »