示例#1
0
        public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }
            if (string.IsNullOrEmpty(text))
            {
                return(Size.Empty);
            }

            WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);

            IntPtr hdc = dc.GetHdc();

            try
            {
                using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc))
                {
                    using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) {
                        return(wg.MeasureText(text, wf, proposedSize));
                    }
                }
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
示例#2
0
        public static Size MeasureText(IDeviceContext dc, string?text, Font?font)
        {
            if (dc == null)
            {
                throw new ArgumentNullException(nameof(dc));
            }
            if (string.IsNullOrEmpty(text))
            {
                return(Size.Empty);
            }

            Gdi32.QUALITY fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);

            IntPtr hdc = dc.GetHdc();

            try
            {
                using WindowsGraphics wg = WindowsGraphics.FromHdc(hdc);
                using WindowsFont? wf    = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality);
                return(wg.MeasureText(text, wf));
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
示例#3
0
        /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText1"]/*' />
        public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, Color backColor)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }

            WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);

            IntPtr hdc = dc.GetHdc();

            try
            {
                using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc))
                {
                    using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) {
                        wg.DrawText(text, wf, pt, foreColor, backColor);
                    }
                }
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
示例#4
0
        /// <include file='doc\TextRenderer.uex' path='docs/doc[@for="TextRenderer.DrawText1"]/*' />
        public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, Color backColor)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }

            WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);

            IntPtr hdc = dc.GetHdc();

            try
            {
                using( WindowsGraphics wg = WindowsGraphics.FromHdc( hdc ))
                {
                    using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality)) {
                        wg.DrawText(text, wf, pt, foreColor, backColor);
                    }
                }
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
示例#5
0
        public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor)
        {
            if (dc == null)
            {
                throw new ArgumentNullException(nameof(dc));
            }

            Gdi32.QUALITY fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);

            IntPtr hdc = dc.GetHdc();

            try
            {
                using (WindowsGraphics wg = WindowsGraphics.FromHdc(hdc))
                {
                    using (WindowsFont wf = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality))
                    {
                        wg.DrawText(text, wf, bounds, foreColor);
                    }
                }
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
        public WindowsGraphicsWrapper( IDeviceContext idc, TextFormatFlags flags)
        {
            if( idc is Graphics )
            {
                ApplyGraphicsProperties properties = ApplyGraphicsProperties.None;

                if( (flags & TextFormatFlags.PreserveGraphicsClipping) != 0)
                {
                    properties |= ApplyGraphicsProperties.Clipping;
                }

                if( (flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0)
                {
                    properties |= ApplyGraphicsProperties.TranslateTransform;
                }

                // Create the WindowsGraphics from the Grahpics object only if Graphics properties need
                // to be reapplied to the DC wrapped by the WindowsGraphics.
                if( properties != ApplyGraphicsProperties.None )
                {
                    this.wg = WindowsGraphics.FromGraphics( idc as Graphics, properties);
                }
            }
            else
            {
                // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly.
                this.wg = idc as WindowsGraphics;

                if( this.wg != null )
                {
                    // In this case we cache the idc to compare it against the wg in the Dispose method to avoid
                    // disposing of the wg.
                    this.idc = idc;
                }
            }

            if( this.wg == null )
            {
                // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or
                // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc.  
                // So create the WindowsGraphics from the hdc directly. 
                // Cache the IDC so the hdc can be released on dispose.
                this.idc = idc;
                this.wg = WindowsGraphics.FromHdc( idc.GetHdc() );
            }

            // Set text padding on the WindowsGraphics (if any).
            if( (flags & TextFormatFlags.LeftAndRightPadding) != 0 )
            {
                wg.TextPadding = TextPaddingOptions.LeftAndRightPadding;
            }
            else if ((flags & TextFormatFlags.NoPadding) != 0 )
            {
                wg.TextPadding = TextPaddingOptions.NoPadding;
            }
            // else wg.TextPadding = TextPaddingOptions.GlyphOverhangPadding - the default value.
        }
示例#7
0
        public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags)
        {
            if (idc is Graphics)
            {
                ApplyGraphicsProperties properties = ApplyGraphicsProperties.None;

                if ((flags & TextFormatFlags.PreserveGraphicsClipping) != 0)
                {
                    properties |= ApplyGraphicsProperties.Clipping;
                }

                if ((flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0)
                {
                    properties |= ApplyGraphicsProperties.TranslateTransform;
                }

                // Create the WindowsGraphics from the Grahpics object only if Graphics properties need
                // to be reapplied to the DC wrapped by the WindowsGraphics.
                if (properties != ApplyGraphicsProperties.None)
                {
                    wg = WindowsGraphics.FromGraphics(idc as Graphics, properties);
                }
            }
            else
            {
                // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly.
                wg = idc as WindowsGraphics;

                if (wg != null)
                {
                    // In this case we cache the idc to compare it against the wg in the Dispose method to avoid
                    // disposing of the wg.
                    this.idc = idc;
                }
            }

            if (wg == null)
            {
                // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or
                // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc.
                // So create the WindowsGraphics from the hdc directly.
                // Cache the IDC so the hdc can be released on dispose.
                this.idc = idc;
                wg       = WindowsGraphics.FromHdc(idc.GetHdc());
            }

            // Set text padding on the WindowsGraphics (if any).
            if ((flags & TextFormatFlags.LeftAndRightPadding) != 0)
            {
                wg.TextPadding = TextPaddingOptions.LeftAndRightPadding;
            }
            else if ((flags & TextFormatFlags.NoPadding) != 0)
            {
                wg.TextPadding = TextPaddingOptions.NoPadding;
            }
            // else wg.TextPadding = TextPaddingOptions.GlyphOverhangPadding - the default value.
        }
示例#8
0
 public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags)
 {
     if (idc is Graphics)
     {
         ApplyGraphicsProperties none = ApplyGraphicsProperties.None;
         if ((flags & TextFormatFlags.PreserveGraphicsClipping) != TextFormatFlags.Default)
         {
             none |= ApplyGraphicsProperties.Clipping;
         }
         if ((flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != TextFormatFlags.Default)
         {
             none |= ApplyGraphicsProperties.TranslateTransform;
         }
         if (none != ApplyGraphicsProperties.None)
         {
             this.wg = System.Windows.Forms.Internal.WindowsGraphics.FromGraphics(idc as Graphics, none);
         }
     }
     else
     {
         this.wg = idc as System.Windows.Forms.Internal.WindowsGraphics;
         if (this.wg != null)
         {
             this.idc = idc;
         }
     }
     if (this.wg == null)
     {
         this.idc = idc;
         this.wg  = System.Windows.Forms.Internal.WindowsGraphics.FromHdc(idc.GetHdc());
     }
     if ((flags & TextFormatFlags.LeftAndRightPadding) != TextFormatFlags.Default)
     {
         this.wg.TextPadding = TextPaddingOptions.LeftAndRightPadding;
     }
     else if ((flags & TextFormatFlags.NoPadding) != TextFormatFlags.Default)
     {
         this.wg.TextPadding = TextPaddingOptions.NoPadding;
     }
 }
 public WindowsGraphicsWrapper(IDeviceContext idc, TextFormatFlags flags)
 {
     if (idc is Graphics)
     {
         ApplyGraphicsProperties none = ApplyGraphicsProperties.None;
         if ((flags & TextFormatFlags.PreserveGraphicsClipping) != TextFormatFlags.Default)
         {
             none |= ApplyGraphicsProperties.Clipping;
         }
         if ((flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != TextFormatFlags.Default)
         {
             none |= ApplyGraphicsProperties.TranslateTransform;
         }
         if (none != ApplyGraphicsProperties.None)
         {
             this.wg = System.Windows.Forms.Internal.WindowsGraphics.FromGraphics(idc as Graphics, none);
         }
     }
     else
     {
         this.wg = idc as System.Windows.Forms.Internal.WindowsGraphics;
         if (this.wg != null)
         {
             this.idc = idc;
         }
     }
     if (this.wg == null)
     {
         this.idc = idc;
         this.wg = System.Windows.Forms.Internal.WindowsGraphics.FromHdc(idc.GetHdc());
     }
     if ((flags & TextFormatFlags.LeftAndRightPadding) != TextFormatFlags.Default)
     {
         this.wg.TextPadding = TextPaddingOptions.LeftAndRightPadding;
     }
     else if ((flags & TextFormatFlags.NoPadding) != TextFormatFlags.Default)
     {
         this.wg.TextPadding = TextPaddingOptions.NoPadding;
     }
 }
 public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor)
 {
     if (dc == null)
     {
         throw new ArgumentNullException("dc");
     }
     WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);
     IntPtr hdc = dc.GetHdc();
     try
     {
         using (WindowsGraphics graphics = WindowsGraphics.FromHdc(hdc))
         {
             using (WindowsFont font2 = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality))
             {
                 graphics.DrawText(text, font2, bounds, foreColor);
             }
         }
     }
     finally
     {
         dc.ReleaseHdc();
     }
 }
示例#11
0
        internal static Size_ MeasureTextInternal(IDeviceContext dc, string text, Font font, Size_ proposedSize, TextFormatFlags flags, bool useMeasureString)
        {
            if (!useMeasureString && !XplatUI.RunningOnUnix)
            {
                // Tell DrawText to calculate Size_ instead of draw
                flags |= (TextFormatFlags)1024;                         // DT_CALCRECT

                IntPtr hdc = dc.GetHdc();

                XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle(new Rectangle_(Point_.Empty, proposedSize));

                IntPtr prevobj;

                if (font != null)
                {
                    prevobj = SelectObject(hdc, font.ToHfont());
                    Win32DrawText(hdc, text, text.Length, ref r, (int)flags);
                    prevobj = SelectObject(hdc, prevobj);
                    DeleteObject(prevobj);
                }
                else
                {
                    Win32DrawText(hdc, text, text.Length, ref r, (int)flags);
                }

                dc.ReleaseHdc();

                // Really, I am just making something up here, which as far as I can tell, MS
                // just makes something up as well.  This will require lots of tweaking to match MS.  :(
                Size_ retval = r.ToRectangle().Size;

                if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0)
                {
                    retval.Width += 6;
                    retval.Width += (int)retval.Height / 8;
                }

                return(retval);
            }
            else
            {
                StringFormat sf = FlagsToStringFormat(flags);

                Size_ retval;

                int proposedWidth;
                if (proposedSize.Width == 0)
                {
                    proposedWidth = Int32.MaxValue;
                }
                else
                {
                    proposedWidth = proposedSize.Width;
                    if ((flags & TextFormatFlags.NoPadding) == 0)
                    {
                        proposedWidth -= 9;
                    }
                }
                if (dc is Graphics)
                {
                    retval = (dc as Graphics).MeasureString(text, font, proposedWidth, sf).ToSize();
                }
                else
                {
                    retval = TextRenderer.MeasureString(text, font, proposedWidth, sf).ToSize();
                }

                if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0)
                {
                    retval.Width += 9;
                }

                return(retval);
            }
        }
示例#12
0
        internal static void DrawTextInternal(IDeviceContext dc, string text, Font font, Rectangle_ bounds, Color_ foreColor, Color_ backColor, TextFormatFlags flags, bool useDrawString)
        {
            if (dc == null)
            {
                throw new ArgumentNullException("dc");
            }

            if (text == null || text.Length == 0)
            {
                return;
            }

            // We use MS GDI API's unless told not to, or we aren't on Windows
            if (!useDrawString && XplatUI.RunningOnUnix)
            {
                if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter || (flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom)
                {
                    flags |= TextFormatFlags.SingleLine;
                }

                // Calculate the text bounds (there is often padding added)
                Rectangle_ new_bounds = PadRectangle(bounds, flags);
                new_bounds.Offset((int)(dc as Graphics).Transform.OffsetX, (int)(dc as Graphics).Transform.OffsetY);

                IntPtr hdc = IntPtr.Zero;
                bool   clear_clip_region = false;

                // If we need to use the graphics clipping region, add it to our hdc
                if ((flags & TextFormatFlags.PreserveGraphicsClipping) == TextFormatFlags.PreserveGraphicsClipping)
                {
                    Graphics graphics    = (Graphics)dc;
                    Region   clip_region = graphics.Clip;

                    if (!clip_region.IsInfinite(graphics))
                    {
                        IntPtr hrgn = clip_region.GetHrgn(graphics);
                        hdc = dc.GetHdc();
                        SelectClipRgn(hdc, hrgn);
                        DeleteObject(hrgn);

                        clear_clip_region = true;
                    }
                }

                if (hdc == IntPtr.Zero)
                {
                    hdc = dc.GetHdc();
                }

                // Set the fore color
                if (foreColor != Color_.Empty)
                {
                    SetTextColor(hdc, ColorTranslator.ToWin32(foreColor));
                }

                // Set the back color
                if (backColor != Color_.Transparent && backColor != Color_.Empty)
                {
                    SetBkMode(hdc, 2);                          //1-Transparent, 2-Opaque
                    SetBkColor(hdc, ColorTranslator.ToWin32(backColor));
                }
                else
                {
                    SetBkMode(hdc, 1);                          //1-Transparent, 2-Opaque
                }

                XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle(new_bounds);

                IntPtr prevobj;

                if (font != null)
                {
                    prevobj = SelectObject(hdc, font.ToHfont());
                    Win32DrawText(hdc, text, text.Length, ref r, (int)flags);
                    prevobj = SelectObject(hdc, prevobj);
                    DeleteObject(prevobj);
                }
                else
                {
                    Win32DrawText(hdc, text, text.Length, ref r, (int)flags);
                }

                if (clear_clip_region)
                {
                    SelectClipRgn(hdc, IntPtr.Zero);
                }

                dc.ReleaseHdc();
            }
            // Use Graphics.DrawString as a fallback method
            else
            {
                Graphics g;
                IntPtr   hdc = IntPtr.Zero;

                if (dc is Graphics)
                {
                    g = (Graphics)dc;
                }
                else
                {
                    hdc = dc.GetHdc();
                    g   = Graphics.FromHdc(hdc);
                }

                StringFormat sf = FlagsToStringFormat(flags);

                Rectangle_ new_bounds = PadDrawStringRectangle(bounds, flags);

                g.DrawString(text, font, ThemeEngine.Current.ResPool.GetSolidBrush(foreColor), new_bounds, sf);

                if (!(dc is Graphics))
                {
                    g.Dispose();
                    dc.ReleaseHdc();
                }
            }
        }
 internal static void CopyPixels(IntPtr sourceHwnd, IDeviceContext targetDC, Point sourceLocation, Point destinationLocation, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
 {
     int width = blockRegionSize.Width;
     int height = blockRegionSize.Height;
     DeviceContext context = DeviceContext.FromHwnd(sourceHwnd);
     HandleRef hDC = new HandleRef(null, targetDC.GetHdc());
     HandleRef hSrcDC = new HandleRef(null, context.Hdc);
     try
     {
         if (!System.Windows.Forms.SafeNativeMethods.BitBlt(hDC, destinationLocation.X, destinationLocation.Y, width, height, hSrcDC, sourceLocation.X, sourceLocation.Y, (int) copyPixelOperation))
         {
             throw new Win32Exception();
         }
     }
     finally
     {
         targetDC.ReleaseHdc();
         context.Dispose();
     }
 }
示例#14
0
		internal static Size MeasureTextInternal (IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags, bool useMeasureString)
		{
			if (!useMeasureString && !XplatUI.RunningOnUnix) {
				// Tell DrawText to calculate size instead of draw
				flags |= (TextFormatFlags)1024;		// DT_CALCRECT

				IntPtr hdc = dc.GetHdc ();

				XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle (new Rectangle (Point.Empty, proposedSize));

				IntPtr prevobj;

				if (font != null) {
					prevobj = SelectObject (hdc, font.ToHfont ());
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
					prevobj = SelectObject (hdc, prevobj);
					DeleteObject (prevobj);
				}
				else {
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
				}

				dc.ReleaseHdc ();

				// Really, I am just making something up here, which as far as I can tell, MS
				// just makes something up as well.  This will require lots of tweaking to match MS.  :(
				Size retval = r.ToRectangle ().Size;

				if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0) {
					retval.Width += 6;
					retval.Width += (int)retval.Height / 8;
				}

				return retval;
			}
			else {
			StringFormat sf = FlagsToStringFormat (flags);

				Size retval;
				
				if (dc is Graphics)
					retval = (dc as Graphics).MeasureString (text, font, proposedSize.Width == 0 ? Int32.MaxValue : proposedSize.Width, sf).ToSize ();
				else
					retval = TextRenderer.MeasureString (text, font, proposedSize.Width == 0 ? Int32.MaxValue : proposedSize.Width, sf).ToSize ();

				if (retval.Width > 0 && (flags & TextFormatFlags.NoPadding) == 0)
					retval.Width += 9;

				return retval;
			}
		}
示例#15
0
		internal static void DrawTextInternal (IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, Color backColor, TextFormatFlags flags, bool useDrawString)
		{
			if (dc == null)
				throw new ArgumentNullException ("dc");

			if (text == null || text.Length == 0)
				return;

			// We use MS GDI API's unless told not to, or we aren't on Windows
			if (!useDrawString && !XplatUI.RunningOnUnix) {
				if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter || (flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom)
					flags |= TextFormatFlags.SingleLine;

				// Calculate the text bounds (there is often padding added)
				Rectangle new_bounds = PadRectangle (bounds, flags);
				new_bounds.Offset ((int)(dc as Graphics).Transform.OffsetX, (int)(dc as Graphics).Transform.OffsetY);

				IntPtr hdc = IntPtr.Zero;
				bool clear_clip_region = false;
				
				// If we need to use the graphics clipping region, add it to our hdc
				if ((flags & TextFormatFlags.PreserveGraphicsClipping) == TextFormatFlags.PreserveGraphicsClipping) {
					Graphics graphics = (Graphics)dc;
					Region clip_region = graphics.Clip;
					
					if (!clip_region.IsInfinite (graphics)) {
						IntPtr hrgn = clip_region.GetHrgn (graphics);
						hdc = dc.GetHdc ();
						SelectClipRgn (hdc, hrgn);
						DeleteObject (hrgn);
						
						clear_clip_region = true;
					}
				}
				
				if (hdc == IntPtr.Zero)
					hdc = dc.GetHdc ();
					
				// Set the fore color
				if (foreColor != Color.Empty)
					SetTextColor (hdc, ColorTranslator.ToWin32 (foreColor));

				// Set the back color
				if (backColor != Color.Transparent && backColor != Color.Empty) {
					SetBkMode (hdc, 2);	//1-Transparent, 2-Opaque
					SetBkColor (hdc, ColorTranslator.ToWin32 (backColor));
				}
				else {
					SetBkMode (hdc, 1);	//1-Transparent, 2-Opaque
				}

				XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle (new_bounds);

				IntPtr prevobj;

				if (font != null) {
					prevobj = SelectObject (hdc, font.ToHfont ());
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
					prevobj = SelectObject (hdc, prevobj);
					DeleteObject (prevobj);
				}
				else {
					Win32DrawText (hdc, text, text.Length, ref r, (int)flags);
				}

				if (clear_clip_region)
					SelectClipRgn (hdc, IntPtr.Zero);

				dc.ReleaseHdc ();
			}
			// Use Graphics.DrawString as a fallback method
			else {
				Graphics g;
				IntPtr hdc = IntPtr.Zero;
				
				if (dc is Graphics)
					g = (Graphics)dc;
				else {
					hdc = dc.GetHdc ();
					g = Graphics.FromHdc (hdc);
				}

				StringFormat sf = FlagsToStringFormat (flags);

				Rectangle new_bounds = PadDrawStringRectangle (bounds, flags);

				g.DrawString (text, font, ThemeEngine.Current.ResPool.GetSolidBrush (foreColor), new_bounds, sf);

				if (!(dc is Graphics)) {
					g.Dispose ();
					dc.ReleaseHdc ();
				}
			}
		}
 public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize)
 {
     Size size;
     if (dc == null)
     {
         throw new ArgumentNullException("dc");
     }
     if (string.IsNullOrEmpty(text))
     {
         return Size.Empty;
     }
     WindowsFontQuality fontQuality = WindowsFont.WindowsFontQualityFromTextRenderingHint(dc as Graphics);
     IntPtr hdc = dc.GetHdc();
     try
     {
         using (WindowsGraphics graphics = WindowsGraphics.FromHdc(hdc))
         {
             using (WindowsFont font2 = WindowsGraphicsCacheManager.GetWindowsFont(font, fontQuality))
             {
                 size = graphics.MeasureText(text, font2, proposedSize);
             }
         }
     }
     finally
     {
         dc.ReleaseHdc();
     }
     return size;
 }
        public WindowsGraphicsWrapper(IDeviceContext deviceContext, TextFormatFlags flags)
        {
            if (deviceContext is Graphics)
            {
                ApplyGraphicsProperties properties = ApplyGraphicsProperties.None;

                if ((flags & TextFormatFlags.PreserveGraphicsClipping) != 0)
                {
                    properties |= ApplyGraphicsProperties.Clipping;
                }

                if ((flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0)
                {
                    properties |= ApplyGraphicsProperties.TranslateTransform;
                }

                // Create the WindowsGraphics from the Grahpics object only if Graphics properties need
                // to be reapplied to the DC wrapped by the WindowsGraphics.
                if (properties != ApplyGraphicsProperties.None)
                {
                    try
                    {
                        _windowsGraphics = WindowsGraphics.FromGraphics(deviceContext as Graphics, properties);
                    }
                    catch
                    {
                        GC.SuppressFinalize(this);
                        throw;
                    }
                }
            }
            else
            {
                // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly.
                _windowsGraphics = deviceContext as WindowsGraphics;

                if (_windowsGraphics != null)
                {
                    // In this case we cache the idc to compare it against the wg in the Dispose method to avoid
                    // disposing of the wg.
                    _deviceContext = deviceContext;
                }
            }

            if (_windowsGraphics == null)
            {
                // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or
                // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc.
                // So create the WindowsGraphics from the hdc directly.
                // Cache the IDC so the hdc can be released ons dispose.
                try
                {
                    _deviceContext   = deviceContext;
                    _windowsGraphics = WindowsGraphics.FromHdc((Gdi32.HDC)deviceContext.GetHdc());
                }
                catch
                {
                    SuppressFinalize();
                    deviceContext.ReleaseHdc();
                    throw;
                }
            }

            // Set text padding on the WindowsGraphics (if any).
            if ((flags & TextFormatFlags.LeftAndRightPadding) != 0)
            {
                _windowsGraphics.TextPadding = TextPaddingOptions.LeftAndRightPadding;
            }
            else if ((flags & TextFormatFlags.NoPadding) != 0)
            {
                _windowsGraphics.TextPadding = TextPaddingOptions.NoPadding;
            }
            // else wg.TextPadding = TextPaddingOptions.GlyphOverhangPadding - the default value.
        }
示例#18
0
		private Padding GetThemeMargins(IDeviceContext dc, MarginTypes marginType) {
			Padding padding;
			try {
				NativeMethods.MARGINS margins;
				IntPtr hdc = dc.GetHdc();
				if (
					NativeMethods.GetThemeMargins(renderer.Handle, hdc, renderer.Part, renderer.State, (int) marginType, IntPtr.Zero,
					                              out margins) == 0) {
					return new Padding(margins.cxLeftWidth, margins.cyTopHeight, margins.cxRightWidth, margins.cyBottomHeight);
				}
				padding = new Padding(0);
			}
			finally {
				dc.ReleaseHdc();
			}
			return padding;
		}
        /// <summary>
        ///  Prefer to use <see cref="DeviceContextHdcScope(IDeviceContext, bool, bool)"/>.
        /// </summary>
        /// <remarks>
        ///  Ideally we'd not bifurcate what properties we apply unless we're absolutely sure we only want one.
        /// </remarks>
        public unsafe DeviceContextHdcScope(
            IDeviceContext deviceContext,
            ApplyGraphicsProperties applyGraphicsState,
            bool saveHdcState = false)
        {
            if (deviceContext is null)
            {
                DisposalTracking.SuppressFinalize(this !);
                throw new ArgumentNullException(nameof(deviceContext));
            }

            DeviceContext  = deviceContext;
            _savedHdcState = 0;

            HDC = default;

            IGraphicsHdcProvider?provider = deviceContext as IGraphicsHdcProvider;
            Graphics?            graphics = deviceContext as Graphics;

            // If we weren't passed a Graphics object we can't save state, so it is effectively the same as apply none.
            // If we were passed an IGraphicsHdcProvider and it tells us we're clean, we also don't need to save state.
            if (applyGraphicsState == ApplyGraphicsProperties.None || graphics is null || provider?.IsGraphicsStateClean == true)
            {
                if (provider is null)
                {
                    // We have an IDeviceContext
                    HDC = (Gdi32.HDC)deviceContext.GetHdc();
                }
                else
                {
                    // We have a provider
                    HDC = provider.GetHDC();

                    if (HDC.IsNull)
                    {
                        graphics = provider.GetGraphics(createIfNeeded: true);
                        if (graphics is null)
                        {
                            throw new InvalidOperationException();
                        }
                        HDC           = (Gdi32.HDC)graphics.GetHdc();
                        DeviceContext = graphics;
                    }
                }

                _savedHdcState = saveHdcState ? Gdi32.SaveDC(HDC) : 0;
                return;
            }

            _savedHdcState = saveHdcState ? Gdi32.SaveDC(HDC) : 0;
            bool applyTransform = applyGraphicsState.HasFlag(ApplyGraphicsProperties.TranslateTransform);
            bool applyClipping  = applyGraphicsState.HasFlag(ApplyGraphicsProperties.Clipping);

            // This API is very expensive
            object[]? data = applyTransform || applyClipping ? (object[])graphics.GetContextInfo() : null;

            using Region? clipRegion     = (Region?)data?[0];
            using Matrix? worldTransform = (Matrix?)data?[1];

            // elements (XFORM) = [eM11, eM12, eM21, eM22, eDx, eDy], eDx/eDy specify the translation offset.
            float[]? elements = applyTransform ? worldTransform?.Elements : null;
            int dx = elements != null ? (int)elements[4] : 0;
            int dy = elements != null ? (int)elements[5] : 0;

            applyTransform = applyTransform && elements != null && (dx != 0 || dy != 0);

            using var graphicsRegion = applyClipping ? new Gdi32.RegionScope(clipRegion !, graphics) : default;
 private Padding GetThemeMargins(IDeviceContext dc, MarginTypes marginType)
 {
     MARGINS margins;
     try
     {
         IntPtr hDC = dc.GetHdc();
         if (0 == GetThemeMargins(_renderer.Handle, hDC, _renderer.Part, _renderer.State, (int) marginType, IntPtr.Zero, out margins))
             return new Padding(margins.cxLeftWidth, margins.cyTopHeight, margins.cxRightWidth, margins.cyBottomHeight);
         return new Padding(0);
     }
     finally
     {
         dc.ReleaseHdc();
     }
 }
        // roughly the same code as in Graphics.cs
        internal static void CopyPixels(IntPtr sourceHwnd, IDeviceContext targetDC, Point sourceLocation, Point destinationLocation, Size blockRegionSize, CopyPixelOperation copyPixelOperation) {
            int destWidth = blockRegionSize.Width;
            int destHeight = blockRegionSize.Height;

            DeviceContext dc = DeviceContext.FromHwnd(sourceHwnd);
            HandleRef targetHDC = new HandleRef( null, targetDC.GetHdc());
            HandleRef screenHDC = new HandleRef( null, dc.Hdc );
            
            try {
                bool result = SafeNativeMethods.BitBlt(targetHDC, destinationLocation.X, destinationLocation.Y, destWidth, destHeight, 
                                                      screenHDC,
                                                      sourceLocation.X, sourceLocation.Y, (int) copyPixelOperation);
                
                //a zero result indicates a win32 exception has been thrown
                if (!result) {
                    throw new Win32Exception();
                }
            }
            finally {
                targetDC.ReleaseHdc();
                dc.Dispose();
            }
        }
 private Padding GetThemeMargins(IDeviceContext dc,
                                 MarginProperty marginType)
 {
   NativeMethods.MARGINS margins;
   try {
     var hDC = dc.GetHdc();
     var rv = NativeMethods.GetThemeMargins(
       renderer.Handle,
       hDC,
       renderer.Part,
       renderer.State,
       (int)marginType,
       IntPtr.Zero,
       out margins);
     if (rv == 0) {
       return new Padding(
         margins.cxLeftWidth,
         margins.cyTopHeight,
         margins.cxRightWidth,
         margins.cyBottomHeight);
     }
     return new Padding(0);
   }
   catch (Exception) {
     return renderer.GetMargins(dc, marginType);
   }
   finally {
     dc.ReleaseHdc();
   }
 }
示例#23
0
        /// <summary>
        /// Draws composited text onto the glass area of a form.
        /// </summary>
        /// <param name="dc">The <see cref="IDeviceContext"/> onto which the composited text should be drawn.</param>
        /// <param name="text">The text to draw.</param>
        /// <param name="font">The <see cref="Font"/> to apply to the drawn text.</param>
        /// <param name="bounds">The <see cref="Rectangle" /> that represents the bounds of the text.</param>
        /// <param name="padding">The <see cref="Padding"/> around the text; necessary to allow space for the glow effect.</param>
        /// <param name="foreColor">The <see cref="Color" /> to apply to the drawn text.</param>
        /// <param name="textFormat">A bitwise combination of the <see cref="TextFormatFlags" /> values.</param>
        /// <param name="glowSize">Specifies the size of a glow that will be drawn on the background prior to any text being drawn.</param>
        /// <remarks>
        /// <para>
        ///   Do not use this method to draw text on non-glass areas of a form.
        /// </para>
        /// </remarks>
        /// <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 void DrawCompositedText(IDeviceContext dc, string text, Font font, Rectangle bounds, Padding padding, Color foreColor, int glowSize, 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
            {
                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);

                    // Draw glowing text
                    System.Windows.Forms.VisualStyles.VisualStyleRenderer renderer = new System.Windows.Forms.VisualStyles.VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active);
                    NativeMethods.DTTOPTS dttOpts = new NativeMethods.DTTOPTS();
                    dttOpts.dwSize = Marshal.SizeOf(typeof(NativeMethods.DTTOPTS));
                    dttOpts.dwFlags = NativeMethods.DrawThemeTextFlags.Composited | NativeMethods.DrawThemeTextFlags.GlowSize | NativeMethods.DrawThemeTextFlags.TextColor;
                    dttOpts.crText = ColorTranslator.ToWin32(foreColor);
                    dttOpts.iGlowSize = glowSize;
                    NativeMethods.RECT textBounds = new NativeMethods.RECT(padding.Left, padding.Top, bounds.Width - padding.Right, bounds.Height - padding.Bottom);
                    NativeMethods.DrawThemeTextEx(renderer.Handle, memoryHdc, 0, 0, text, text.Length, (int)textFormat, ref textBounds, ref dttOpts);

                    // Copy to foreground
                    const int SRCCOPY = 0x00CC0020;
                    NativeMethods.BitBlt(primaryHdc, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memoryHdc, 0, 0, SRCCOPY);
                }
            }
            finally
            {
                dc.ReleaseHdc();
            }
        }
示例#24
0
        /// <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();
            }
        }