Beispiel #1
0
        ///  GetTextMargins - checks to see if we have cached information about the current font,
        ///  returns info about it.
        ///  An MRU of Font margins was considered, but seems like overhead.
        internal static Interop.User32.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font)
        {
            // PERF: operate on a local reference rather than party directly on the thread static one.
            CachedInfo currentCachedInfo = cachedMeasurementDCInfo;

            if (currentCachedInfo != null && currentCachedInfo.LeftTextMargin > 0 && currentCachedInfo.RightTextMargin > 0 && font == currentCachedInfo.LastUsedFont)
            {
                // we have to return clones as DrawTextEx will modify this struct
                return(new Interop.User32.DRAWTEXTPARAMS
                {
                    iLeftMargin = currentCachedInfo.LeftTextMargin,
                    iRightMargin = currentCachedInfo.RightTextMargin
                });
            }
            else if (currentCachedInfo == null)
            {
                currentCachedInfo       = new CachedInfo();
                cachedMeasurementDCInfo = currentCachedInfo;
            }
            Interop.User32.DRAWTEXTPARAMS drawTextParams = wg.GetTextMargins(font);
            currentCachedInfo.LeftTextMargin  = drawTextParams.iLeftMargin;
            currentCachedInfo.RightTextMargin = drawTextParams.iRightMargin;

            // returning a copy here to be consistent with the return value from the cache.
            return(new Interop.User32.DRAWTEXTPARAMS
            {
                iLeftMargin = currentCachedInfo.LeftTextMargin,
                iRightMargin = currentCachedInfo.RightTextMargin
            });
        }
Beispiel #2
0
        /// <summary>
        ///  The GDI DrawText does not do multiline alignment when Interop.User32.TextFormatFlags.DT_SINGLELINE is not set. This
        ///  adjustment is to workaround that limitation. We don't want to duplicate SelectObject calls here,
        ///  so put your Font in the dc before calling this.
        ///
        ///  AdjustForVerticalAlignment is only used when the text is multiline and it fits inside the bounds passed in.
        ///  In that case we want the horizontal center of the multiline text to be at the horizontal center of the bounds.
        ///
        ///  If the text is multiline and it does not fit inside the bounds passed in, then return the bounds that were passed in.
        ///  This way we paint the top of the text at the top of the bounds passed in.
        /// </summary>
        public static Rectangle AdjustForVerticalAlignment(HandleRef hdc, string text, Rectangle bounds, Interop.User32.TextFormatFlags flags, ref Interop.User32.DRAWTEXTPARAMS dtparams)
        {
            Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!");

            // Ok if any Top (Cannot test Interop.User32.TextFormatFlags.Top because it is 0), single line text or measuring text.
            bool isTop = (flags & Interop.User32.TextFormatFlags.DT_BOTTOM) == 0 && (flags & Interop.User32.TextFormatFlags.DT_VCENTER) == 0;

            if (isTop || ((flags & Interop.User32.TextFormatFlags.DT_SINGLELINE) != 0) || ((flags & Interop.User32.TextFormatFlags.DT_CALCRECT) != 0))
            {
                return(bounds);
            }

            Interop.RECT rect = new Interop.RECT(bounds);

            // Get the text bounds.
            flags |= Interop.User32.TextFormatFlags.DT_CALCRECT;
            int textHeight = Interop.User32.DrawTextExW(hdc, text, text.Length, ref rect, flags, ref dtparams);

            // if the text does not fit inside the bounds then return the bounds that were passed in
            if (textHeight > bounds.Height)
            {
                return(bounds);
            }

            Rectangle adjustedBounds = bounds;

            if ((flags & Interop.User32.TextFormatFlags.DT_VCENTER) != 0)  // Middle
            {
                adjustedBounds.Y = adjustedBounds.Top + adjustedBounds.Height / 2 - textHeight / 2;
            }
            else // Bottom.
            {
                adjustedBounds.Y = adjustedBounds.Bottom - textHeight;
            }

            return(adjustedBounds);
        }
Beispiel #3
0
        /// <summary>
        ///  Returns the Size in logical units of the given text using the given Font, and according to the formatting flags.
        ///  The proposed size is used to create a bounding rectangle as follows:
        ///  - If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by
        ///  the lpRect parameter and extends the base of the rectangle to bound the last line of text.
        ///  - If the largest word is wider than the rectangle, the width is expanded.
        ///  - If the text is less than the width of the rectangle, the width is reduced.
        ///  - If there is only one line of text, DrawText modifies the right side of the rectangle so that
        ///  it bounds the last character in the line.
        ///  If the font is null, the hdc's current font will be used.
        ///
        ///  Note for vertical fonts (if ever supported): DrawTextEx uses GetTextExtentPoint32 for measuring the text and this
        ///  function has the following limitation (from MSDN):
        ///  - This function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both
        ///  the horizontal and vertical measurements of the text.  The application must convert it explicitly.
        /// </summary>
        public Size MeasureText(string text, WindowsFont font, Size proposedSize, Interop.User32.TextFormatFlags flags)
        {
            Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!");

            if (string.IsNullOrEmpty(text))
            {
                return(Size.Empty);
            }

            // DrawText returns a rectangle useful for aligning, but not guaranteed to encompass all
            // pixels (its not a FitBlackBox, if the text is italicized, it will overhang on the right.)
            // So we need to account for this.
#if OPTIMIZED_MEASUREMENTDC
            Interop.User32.DRAWTEXTPARAMS dtparams;
            // use the cache if we've got it
            if (MeasurementDCInfo.IsMeasurementDC(DeviceContext))
            {
                dtparams = MeasurementDCInfo.GetTextMargins(this, font);
            }
            else
            {
                dtparams = GetTextMargins(font);
            }
#else
            Interop.User32.DRAWTEXTPARAMS dtparams = GetTextMargins(font);
#endif

            // If Width / Height are < 0, we need to make them larger or DrawText will return
            // an unbounded measurement when we actually trying to make it very narrow.
            int minWidth = 1 + dtparams.iLeftMargin + dtparams.iRightMargin;

            if (proposedSize.Width <= minWidth)
            {
                proposedSize.Width = minWidth;
            }
            if (proposedSize.Height <= 0)
            {
                proposedSize.Height = 1;
            }

            var rect = new Interop.RECT(0, 0, proposedSize.Width, proposedSize.Height);
            if (font != null)
            {
                dc.SelectFont(font);
            }

            // If proposedSize.Height >= MaxSize.Height it is assumed bounds needed.  If flags contain DT_SINGLELINE and
            // DT_VCENTER or DT_BOTTOM options, DrawTextEx does not bind the rectangle to the actual text height since
            // it assumes the text is to be vertically aligned; we need to clear the DT_VCENTER and DT_BOTTOM flags to
            // get the actual text bounds.
            if (proposedSize.Height >= MaxSize.Height && (flags & Interop.User32.TextFormatFlags.DT_SINGLELINE) != 0)
            {
                // Clear vertical-alignment flags.
                flags &= ~(Interop.User32.TextFormatFlags.DT_BOTTOM | Interop.User32.TextFormatFlags.DT_VCENTER);
            }

            if (proposedSize.Width == MaxSize.Width)
            {
                // PERF: No constraining width means no word break.
                // in this case, we dont care about word wrapping - there should be enough room to fit it all
                flags &= ~(Interop.User32.TextFormatFlags.DT_WORDBREAK);
            }

            flags |= Interop.User32.TextFormatFlags.DT_CALCRECT;
            Interop.User32.DrawTextExW(dc.Hdc, text, text.Length, ref rect, flags, ref dtparams);

            return(rect.Size);
        }
Beispiel #4
0
        /// <summary>
        ///  Draws the text in the given bounds, using the given Font, foreColor and backColor, and according to the specified
        ///  TextFormatFlags flags.
        ///  If font is null, the font currently selected in the hdc is used.
        ///  If foreColor and/or backColor are Color.Empty, the hdc current text and/or background color are used.
        /// </summary>
        public void DrawText(string text, WindowsFont font, Rectangle bounds, Color foreColor, Color backColor, Interop.User32.TextFormatFlags flags)
        {
            if (string.IsNullOrEmpty(text) || foreColor == Color.Transparent)
            {
                return;
            }

            Debug.Assert(((uint)flags & GdiUnsupportedFlagMask) == 0, "Some custom flags were left over and are not GDI compliant!");
            Debug.Assert((flags & Interop.User32.TextFormatFlags.DT_CALCRECT) == 0, "DT_CALCRECT flag is set, text won't be drawn");

            HandleRef hdc = new HandleRef(dc, dc.Hdc);

            // DrawText requires default text alignment.
            if (dc.TextAlignment != DeviceContextTextAlignment.Default)
            {
                dc.SetTextAlignment(DeviceContextTextAlignment.Default);
            }

            // color empty means use the one currently selected in the dc.

            if (!foreColor.IsEmpty && foreColor != dc.TextColor)
            {
                dc.SetTextColor(foreColor);
            }

            if (font != null)
            {
                dc.SelectFont(font);
            }

            DeviceContextBackgroundMode newBackGndMode = (backColor.IsEmpty || backColor == Color.Transparent) ?
                                                         DeviceContextBackgroundMode.Transparent :
                                                         DeviceContextBackgroundMode.Opaque;

            if (dc.BackgroundMode != newBackGndMode)
            {
                dc.SetBackgroundMode(newBackGndMode);
            }

            if (newBackGndMode != DeviceContextBackgroundMode.Transparent && backColor != dc.BackgroundColor)
            {
                dc.SetBackgroundColor(backColor);
            }

            Interop.User32.DRAWTEXTPARAMS dtparams = GetTextMargins(font);

            bounds = AdjustForVerticalAlignment(hdc, text, bounds, flags, ref dtparams);

            // Adjust unbounded rect to avoid overflow since Rectangle ctr does not do param validation.
            if (bounds.Width == MaxSize.Width)
            {
                bounds.Width -= bounds.X;
            }
            if (bounds.Height == MaxSize.Height)
            {
                bounds.Height -= bounds.Y;
            }

            var rect = new Interop.RECT(bounds);

            Interop.User32.DrawTextExW(hdc, text, text.Length, ref rect, flags, ref dtparams);

            // No need to restore previous objects into the dc (see comments on top of the class).
        }