/// <summary> /// Provides the size, in pixels, of the specified text. /// </summary> /// <param name="dc">The device context in which to measure the text.</param> /// <param name="text">The text to measure.</param> /// <param name="font">The <see cref="Font"/> to apply to the measured text.</param> /// <param name="textFormat">A bitwise combination of the <see cref="TextFormatFlags" /> values.</param> /// <returns>The <see cref="Size"/>, in pixels, of <paramref name="text"/> drawn with the specified <paramref name="font"/> and format.</returns> /// <exception cref="NotSupportedException">The current operating system does not support glass, or the Desktop Window Manager is not enabled.</exception> /// <exception cref="ArgumentNullException"><paramref name="dc"/>, <paramref name="text"/> or <paramref name="font"/> is <see langword="null"/>.</exception> public static Size MeasureCompositedText(IDeviceContext dc, string text, Font font, TextFormatFlags textFormat) { if (!IsDwmCompositionEnabled) { throw new NotSupportedException(Properties.Resources.GlassNotSupportedError); } if (dc == null) { throw new ArgumentNullException("dc"); } if (text == null) { throw new ArgumentNullException("text"); } if (font == null) { throw new ArgumentNullException("font"); } IntPtr primaryHdc = dc.GetHdc(); try { Rectangle bounds = new Rectangle(0, 0, int.MaxValue, int.MaxValue); using (SafeDeviceHandle memoryHdc = NativeMethods.CreateCompatibleDC(primaryHdc)) using (SafeGDIHandle fontHandle = new SafeGDIHandle(font.ToHfont(), true)) using (SafeGDIHandle dib = NativeMethods.CreateDib(bounds, primaryHdc, memoryHdc)) { NativeMethods.SelectObject(memoryHdc, fontHandle); System.Windows.Forms.VisualStyles.VisualStyleRenderer renderer = new System.Windows.Forms.VisualStyles.VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active); NativeMethods.RECT bounds2 = new NativeMethods.RECT(bounds); NativeMethods.RECT rect; NativeMethods.GetThemeTextExtent(renderer.Handle, memoryHdc, 0, 0, text, text.Length, (int)textFormat, ref bounds2, out rect); return(new Size(rect.Right - rect.Left, rect.Bottom - rect.Top)); } } finally { dc.ReleaseHdc(); } }
public static extern IntPtr SelectObject(SafeDeviceHandle hDC, SafeGDIHandle hObject);