public static int GetTextBaseline(Control ctrl, ContentAlignment alignment) { if (ctrl == null) { throw new ArgumentNullException("ctrl"); } Rectangle ctrlRect = ctrl.ClientRectangle; int ascent = 0; int height = 0; using (Graphics grfx = ctrl.CreateGraphics()) { IntPtr hDC = grfx.GetHdc(); IntPtr hFont = ctrl.Font.ToHfont(); try { IntPtr oldFont = Gdi32.SelectObject(hDC, hFont); TEXTMETRIC textMetric = new TEXTMETRIC(); Gdi32.GetTextMetrics(hDC, textMetric); ascent = textMetric.tmAscent + 1; height = textMetric.tmHeight; Gdi32.SelectObject(hDC, oldFont); } finally { Gdi32.DeleteObject(hFont); grfx.ReleaseHdc(hDC); } } if ((alignment & NuGenControlPaint.AnyTop) != 0) { return (ctrlRect.Top + ascent); } if ((alignment & NuGenControlPaint.AnyMiddle) != 0) { return (((ctrlRect.Top + (ctrlRect.Height / 2)) - (height / 2)) + ascent); } return ((ctrlRect.Bottom - height) + ascent); }
public static extern Boolean GetTextMetrics(IntPtr hdc, TEXTMETRIC tm);