예제 #1
0
        public static Size GetTextSize(Graphics graphics, string text, Font font)
        {
            IntPtr hdc = IntPtr.Zero;

            if (graphics != null)
            {
                // Get device context from the graphics passed in
                hdc = graphics.GetHdc();
            }
            else
            {
                // Get screen device context
                hdc = APIsGdi.GetDC(IntPtr.Zero);
            }

            IntPtr fontHandle        = font.ToHfont();
            IntPtr currentFontHandle = APIsGdi.SelectObject(hdc, fontHandle);

            APIsStructs.RECT rect = new APIsStructs.RECT();
            rect.left   = 0;
            rect.right  = 0;
            rect.top    = 0;
            rect.bottom = 0;

            APIsUser32.DrawText(hdc, text, text.Length, ref rect,
                                APIsEnums.DrawTextFormatFlags.SINGLELINE | APIsEnums.DrawTextFormatFlags.LEFT | APIsEnums.DrawTextFormatFlags.CALCRECT);
            APIsGdi.SelectObject(hdc, currentFontHandle);
            APIsGdi.DeleteObject(fontHandle);

            if (graphics != null)
            {
                graphics.ReleaseHdc(hdc);
            }
            else
            {
                APIsUser32.ReleaseDC(IntPtr.Zero, hdc);
            }

            return(new Size(rect.right - rect.left, rect.bottom - rect.top));
        }