internal void Dispose(bool disposing) { if (_disposed) { return; } Disposing?.Invoke(this, EventArgs.Empty); _disposed = true; DisposeFont(disposing); switch (DeviceContextType) { case DeviceContextType.Display: Debug.Assert(disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from."); ((IDeviceContext)this).ReleaseHdc(); break; case DeviceContextType.Information: case DeviceContextType.NamedDevice: // CreateDC and CreateIC add an HDC handle to the HandleCollector; to remove it properly we need // to call DeleteHDC. #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(String.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked ((int)this.hDC)))); #endif Gdi32.DeleteDC(_hDC); _hDC = IntPtr.Zero; break; case DeviceContextType.Memory: // CreatCompatibleDC adds a GDI handle to HandleCollector, to remove it properly we need to call // DeleteDC. #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(String.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked ((int)this.hDC)))); #endif Gdi32.DeleteDC(_hDC); _hDC = IntPtr.Zero; break; case DeviceContextType.Unknown: default: return; // do nothing, the hdc is not owned by this object. // in this case it is ok if disposed throught finalization. } DbgUtil.AssertFinalization(this, disposing); }
static public void DrawXORRectangle(Graphics graphics, Pen pen, Rectangle rectangle) { IntPtr hDC = graphics.GetHdc(); IntPtr hPen = Gdi32.CreatePen(0, (int)pen.Width, ArgbToRGB(pen.Color.ToArgb())); Gdi32.SelectObject(hDC, hPen); Gdi32.SetROP2(hDC, (int)Gdi32.DrawingMode.R2_NOTXORPEN); Gdi32.Rectangle(hDC, rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom); Gdi32.DeleteObject(hPen); graphics.ReleaseHdc(hDC); }
private static void Initialize() { if (s_isInitialized) { return; } using var dc = User32.GetDcScope.ScreenDC; s_deviceDpi = Gdi32.GetDeviceCaps(dc, Gdi32.DeviceCapability.LOGPIXELSX); s_isInitialized = true; }
private static void Initialize() { if (isInitialized) { return; } using ScreenDC dc = ScreenDC.Create(); deviceDpi = Gdi32.GetDeviceCaps(dc, Gdi32.DeviceCapability.LOGPIXELSX); isInitialized = true; }
/// <summary> /// Draws scanned image to an image object /// </summary> /// <param name="image"></param> public void CopyTo(Image image) { Debug.Assert(image != null); using (Graphics g = Graphics.FromImage(image)) { IntPtr hdc = g.GetHdc(); Gdi32.SetDIBitsToDevice(hdc, 0, 0, image.Width, image.Height, 0, 0, 0, Rect.Height, PxPtr, BmpPtr, 0); g.ReleaseHdc(hdc); } }
public NotificationForm(string title, string desc) { InitializeComponent(); this.components.SetStyle(this); Region = Region.FromHrgn(Gdi32.CreateRoundRectRgn(0, 0, Width, Height, 0, 0)); // this.lbl_title.Text = title; this.txtBox_desc.Text = desc; lbl_time.Text = DateTime.Now.ToString("HH:mm"); }
public static FontCache.Scope GetHFONT(Font?font, Gdi32.QUALITY quality, Gdi32.HDC hdc) { if (font != null) { return(GetHFONT(font, quality)); } // Font is null, build off of the specified HDC's current font. Gdi32.HFONT hfont = (Gdi32.HFONT)Gdi32.GetCurrentObject(hdc, Gdi32.OBJ.FONT); return(new FontCache.Scope(hfont));; }
internal void Close() { if (Region != IntPtr.Zero) { User32.SetWindowRgn(Handle, IntPtr.Zero, false); Gdi32.DeleteObject(Region); } User32.CloseWindow(Handle); User32.SetParent((int)Handle, 0); User32.DestroyWindow(Handle); }
public void ResetFont() { #if OPTIMIZED_MEASUREMENTDC // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. MeasurementDCInfo.ResetIfIsMeasurementDC(Hdc); #endif Gdi32.SelectObject(new HandleRef(this, Hdc), hInitialFont); selectedFont = null; hCurrentFont = hInitialFont; }
public Color GetColor(int x, int y) { IntPtr hdc = User32.GetDC(IntPtr.Zero); uint pixel = Gdi32.GetPixel(hdc, x, y); User32.ReleaseDC(IntPtr.Zero, hdc); Color color = Color.FromArgb((int)(pixel & 0x000000FF), (int)(pixel & 0x0000FF00) >> 8, (int)(pixel & 0x00FF0000) >> 16); return(color); }
/// <summary>Rounds the region of the control.</summary> /// <param name="control">The control to round.</param> /// <param name="rounding">The amount of rounding.</param> public static void RoundRegion(Control control, int rounding) { try { control.Region = Region.FromHrgn(Gdi32.CreateRoundRectRgn(0, 0, control.Width, control.Height, rounding, rounding)); } catch (Exception e) { Console.WriteLine(e); throw; } }
// Not all state is handled yet. Backfilling in as we write specific tests. Of special note is that we don't // have tracking for Save/RestoreDC yet. /// <summary> /// Initialize the current state of <paramref name="hdc"/>. /// </summary> public DeviceContextState(Gdi32.HDC hdc) { MapMode = Gdi32.GetMapMode(hdc); BackColor = Gdi32.GetBkColor(hdc); TextColor = Gdi32.GetTextColor(hdc); Point point = default; Gdi32.GetBrushOrgEx(hdc, ref point); BrushOrigin = point; TextAlign = Gdi32.GetTextAlign(hdc); BackgroundMode = Gdi32.GetBkMode(hdc); }
static public void DrawXORLine(Graphics graphics, Pen pen, int x1, int y1, int x2, int y2) { IntPtr hDC = graphics.GetHdc(); IntPtr hPen = Gdi32.CreatePen(0, (int)pen.Width, ArgbToRGB(pen.Color.ToArgb())); Gdi32.SelectObject(hDC, hPen); Gdi32.SetROP2(hDC, (int)Gdi32.DrawingMode.R2_NOTXORPEN); Gdi32.MoveToEx(hDC, x1, y1, ref nullPoint); Gdi32.LineTo(hDC, x2, y2); Gdi32.DeleteObject(hPen); graphics.ReleaseHdc(hDC); }
/// <para>Changes the current bitmap with a custom opacity level. Here is where all happens!</para> public void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); } // The ideia of this is very simple, // 1. Create a compatible DC with screen; // 2. Select the bitmap with 32bpp with alpha-channel in the compatible DC; // 3. Call the UpdateLayeredWindow. var screenDc = Win32.GetDC(IntPtr.Zero); using (var memDc = new Gdi32.SafeDCHandle(Gdi32.CreateCompatibleDC(screenDc))) { var hBitmap = IntPtr.Zero; var oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); // grab a GDI handle from this GDI+ bitmap oldBitmap = Gdi32.SelectObject(memDc, hBitmap); var size = new Win32.Size(bitmap.Width, bitmap.Height); var pointSource = new Win32.Point(0, 0); var topPos = new Win32.Point(Left, Top); var blend = new Win32.Blendfunction { BlendOp = Win32.AcSrcOver, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = Win32.AcSrcAlpha }; Win32.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc.DangerousGetHandle(), ref pointSource, 0, ref blend, Win32.UlwAlpha); } finally { Win32.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { Gdi32.SelectObject(memDc, oldBitmap); //Windows.DeleteObject(hBitmap); // The documentation says that we have to use the Windows.DeleteObject... but since there is no such method I use the normal DeleteObject from Win32 GDI and it's working fine without any resource leak. Gdi32.DeleteObject(hBitmap); Size = bitmap.Size; } } } }
public static BitmapSource GetImageSourceFromBitmap(Bitmap bmp) { IntPtr hBmp = bmp.GetHbitmap(); BitmapSource src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBmp, IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); Gdi32.DeleteObject(hBmp); return(src); }
/* * DrawPoint */ /// <summary> /// Draws the point on the specified graphics surface with the specified color at the specified /// coordinates. /// </summary> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="g"/> is <see langword="null"/>. /// </exception> public static void DrawPoint(Graphics g, Color color, int x, int y) { if (g == null) { throw new ArgumentNullException("g"); } IntPtr hDC = g.GetHdc(); Gdi32.SetPixelV(hDC, x, y, color); g.ReleaseHdc(hDC); }
protected override void CreateBrush() { IntPtr nativeHandle = Gdi32.CreateSolidBrush(ColorTranslator.ToWin32(Color)); // Don't use Debug.Assert, DbgUtil.GetLastErrorStr would always be evaluated. if (nativeHandle == IntPtr.Zero) { Debug.Fail("CreateSolidBrush failed : " + DbgUtil.GetLastErrorStr()); } HBrush = nativeHandle; }
private void _IconsLoadingThreadRun() { while (true) { if (this._ShellViewEx != null && this._ShellViewEx.IsSearchNavigating) { Thread.Sleep(1); Application.DoEvents(); } var index = 0; if (!ThreadRun_Helper(this._IconsForRetreval, false, ref index)) { continue; } var sho = this._ShellViewEx.Items[index]; var clonedSho = sho.Clone(); if (!sho.IsIconLoaded || !sho.IsRCWSet) { try { //Thread.Sleep(1); //Application.DoEvents(); //var temp = FileSystemListItem.ToFileSystemItem(sho.ParentHandle, sho.ParsingName.ToShellParsingName()); var icon = clonedSho.GetHBitmap(this._CurrentSize, false, true); var shieldOverlay = 0; if (sho.ShieldedIconIndex == -1) { if ((clonedSho.GetShield() & IExtractIconPWFlags.GIL_SHIELD) != 0) { shieldOverlay = this._ShieldIconIndex; } sho.ShieldedIconIndex = shieldOverlay; } if (icon != IntPtr.Zero || shieldOverlay > 0) { sho.IsIconLoaded = true; sho.IsRCWSet = true; Gdi32.DeleteObject(icon); if (!this._RedrawQueue.Contains(index)) { this._RedrawQueue.Enqueue(index); } // this._ShellViewEx.RedrawItem(index); } //Catch File not found exception since it happens if the file is laready deleted } catch (FileNotFoundException) { } } clonedSho.Dispose(); sho.Dispose(); } }
private void DrawNCArea(IntPtr hRgn) { Region clipRegion = null; if (hRgn != TRUE) { clipRegion = Region.FromHrgn(hRgn); } RECT windowRect = new RECT(); RECT nclientRect = new RECT(); RECT clientRect = new RECT(); User32.GetWindowRect(parentWindowHWnd, ref windowRect); User32.OffsetRect(ref windowRect, -windowRect.left, -windowRect.top); var height = windowRect.bottom; var width = windowRect.right; User32.GetClientRect(parentWindowHWnd, ref clientRect); User32.OffsetRect(ref clientRect, -clientRect.left, -clientRect.top); User32.GetClientRect(parentWindowHWnd, ref nclientRect); User32.OffsetRect(ref nclientRect, -clientRect.left, -clientRect.top); User32.OffsetRect(ref nclientRect, borderSize, borderSize); IntPtr hDC = User32.GetWindowDC(parentWindowHWnd); var windowRectangle = new Rectangle(windowRect.left, windowRect.top, (int)windowRect.Width, (int)windowRect.Height); var clientRectangle = new Rectangle(nclientRect.left, nclientRect.top, (int)clientRect.Height, (int)clientRect.Width); try { COLORREF color = new COLORREF(borderColor); IntPtr hBrush = Gdi32.CreateSolidBrush(color.ColorDWORD); Gdi32.ExcludeClipRect(hDC, nclientRect.left, nclientRect.top, nclientRect.right, nclientRect.bottom); User32.FillRect(hDC, ref windowRect, hBrush); Gdi32.DeleteObject(hBrush); } catch (Exception ex) { } finally { User32.ReleaseDC(parentWindowHWnd, hDC); } }
private unsafe void MirrorDcIfNeeded(Gdi32.HDC hdc) { if (_parent.IsMirrored) { // Mirror the DC Gdi32.SetMapMode(hdc, Gdi32.MM.ANISOTROPIC); Gdi32.GetViewportExtEx(hdc, out Size originalExtents); Gdi32.SetViewportExtEx(hdc, -originalExtents.Width, originalExtents.Height, null); Gdi32.GetViewportOrgEx(hdc, out Point originalOrigin); Gdi32.SetViewportOrgEx(hdc, originalOrigin.X + _windowBounds.Width - 1, originalOrigin.Y, null); } }
public AccSettings() { InitializeComponent(); this.components.SetStyle(this); Region = Region.FromHrgn(Gdi32.CreateRoundRectRgn(0, 0, Width, Height, 5, 5)); foreach (var button in this.Controls.OfType <MetroFramework.Controls.MetroButton>()) { IntPtr ptr = Gdi32.CreateRoundRectRgn(1, 1, button.Width, button.Height, 5, 5); button.Region = Region.FromHrgn(ptr); Gdi32.DeleteObject(ptr); } }
public Rectangle ToRectangle() { if (IsInfinite) { return(new Rectangle(-int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue)); } var rect = new RECT(); Gdi32.GetRgnBox(new HandleRef(this, nativeHandle), ref rect); return(new Rectangle(new Point(rect.left, rect.top), rect.Size)); }
internal unsafe static void DrawLine(this Gdi32.HDC hdc, Gdi32.HPEN pen, int x1, int y1, int x2, int y2) { using var ropScope = new Gdi32.SetRop2Scope(hdc, Gdi32.R2.COPYPEN); using var bkScope = new Gdi32.SetBkModeScope(hdc, Gdi32.BKMODE.TRANSPARENT); using var selection = new Gdi32.SelectObjectScope(hdc, pen); Point oldPoint = new Point(); Gdi32.MoveToEx(hdc, x1, y1, &oldPoint); Gdi32.LineTo(hdc, x2, y2); Gdi32.MoveToEx(hdc, oldPoint.X, oldPoint.Y, &oldPoint); }
public AddAcc() { InitializeComponent(); this.Activate(); this.components.SetStyle(this); this.FormBorderStyle = FormBorderStyle.None; Region = System.Drawing.Region.FromHrgn(Gdi32.CreateRoundRectRgn(0, 0, Width, Height, 5, 5)); IntPtr ptr = Gdi32.CreateRoundRectRgn(1, 1, btn_addAcc.Width, btn_addAcc.Height, 5, 5); btn_addAcc.Region = Region.FromHrgn(ptr); Gdi32.DeleteObject(ptr); }
// capture a region of a the screen, defined by the hWnd public static BitmapSource CaptureRegion( IntPtr hWnd, int x, int y, int width, int height, bool addToClipboard) { IntPtr sourceDC = IntPtr.Zero; IntPtr targetDC = IntPtr.Zero; IntPtr compatibleBitmapHandle = IntPtr.Zero; BitmapSource bitmap = null; try { // gets the main desktop and all open windows sourceDC = User32.GetDC(User32.GetDesktopWindow()); //sourceDC = User32.GetDC(hWnd); targetDC = Gdi32.CreateCompatibleDC(sourceDC); // create a bitmap compatible with our target DC compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height); // gets the bitmap into the target device context Gdi32.SelectObject(targetDC, compatibleBitmapHandle); // copy from source to destination Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.SRCCOPY); // Here's the WPF glue to make it all work. It converts from an // hBitmap to a BitmapSource. Love the WPF interop functions bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (addToClipboard) { //Clipboard.SetImage(bitmap); // high memory usage for large images IDataObject data = new DataObject(); data.SetData(DataFormats.Dib, bitmap, false); Clipboard.SetDataObject(data, false); } } catch (Exception ex) { throw new ScreenCaptureException(string.Format("Error capturing region {0},{1},{2},{3}", x, y, width, height), ex); } finally { Gdi32.DeleteObject(compatibleBitmapHandle); User32.ReleaseDC(IntPtr.Zero, sourceDC); User32.ReleaseDC(IntPtr.Zero, targetDC); } return(bitmap); }
/// <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 static void DrawText( this Gdi32.HDC hdc, ReadOnlySpan <char> text, FontCache.Scope font, Rectangle bounds, Color foreColor, User32.DT flags, Color backColor = default, TextPaddingOptions padding = default) { if (text.IsEmpty || foreColor == Color.Transparent) { return; } ValidateFlags(flags); // DrawText requires default text alignment. using var alignment = new Gdi32.SetTextAlignmentScope(hdc, default); // Color empty means use the one currently selected in the dc. using var textColor = foreColor.IsEmpty ? default : new Gdi32.SetTextColorScope(hdc, foreColor); using var fontSelection = new Gdi32.SelectObjectScope(hdc, (Gdi32.HFONT)font); Gdi32.BKMODE newBackGroundMode = (backColor.IsEmpty || backColor == Color.Transparent) ? Gdi32.BKMODE.TRANSPARENT : Gdi32.BKMODE.OPAQUE; using var backgroundMode = new Gdi32.SetBkModeScope(hdc, newBackGroundMode); using var backgroundColor = newBackGroundMode != Gdi32.BKMODE.TRANSPARENT ? new Gdi32.SetBackgroundColorScope(hdc, backColor) : default; User32.DRAWTEXTPARAMS dtparams = GetTextMargins(font, padding); 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 == TextRenderer.MaxSize.Width) { bounds.Width -= bounds.X; } if (bounds.Height == TextRenderer.MaxSize.Height) { bounds.Height -= bounds.Y; } RECT rect = bounds; User32.DrawTextExW(hdc, text, ref rect, flags, ref dtparams); }
public override void Create() { this.wndProc = new WndProc(WndProc); WndClass wndClass; wndClass.style = ClassStyles.HorizontalRedraw | ClassStyles.VerticalRedraw | ClassStyles.OwnDC; wndClass.lpfnWndProc = wndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = User32.LoadIcon(IntPtr.Zero, SystemIcons.Application); wndClass.hCursor = User32.LoadCursor(IntPtr.Zero, IdcStandardCursors.Arrow); wndClass.hbrBackground = Gdi32.GetStockObject(StockObjects.BlackBrush); wndClass.lpszMenuName = null; wndClass.lpszClassName = className; if (User32.RegisterClass(ref wndClass) == 0) { throw new WindowException("RegisterClass failed"); } WindowStyles dwStyle = WindowStyles.Popup | WindowStyles.ClipChildren | WindowStyles.ClipSiblings; if (Mode == WindowMode.Windowed) { dwStyle |= WindowStyles.SysMenu | WindowStyles.Caption; } Handle = User32.CreateWindowEx( WindowStylesEx.Left, className, Title, dwStyle, X, Y, Width, Height, IntPtr.Zero, // hWndParent IntPtr.Zero, // hMenu hInstance, IntPtr.Zero); // lpParam if (Handle == IntPtr.Zero) { throw new WindowException("CreateWindowEx failed"); } OnCreated(); AdjustWindow(X, Y, Width, Height); }
internal static void GetDevicePixels(HandleRef handleRef, out double x, out double y) { x = LogicalDpi; y = LogicalDpi; Gdi32.HDC hDC = User32.GetDC(handleRef); if (!hDC.IsNull) { x = Gdi32.GetDeviceCaps(hDC, Gdi32.DeviceCapability.LOGPIXELSX); y = Gdi32.GetDeviceCaps(hDC, Gdi32.DeviceCapability.LOGPIXELSY); User32.ReleaseDC(handleRef, hDC); } }
private bool GetTextExtentPoint32(char item, out Size size) { size = new Size(); using var hdc = new GetDcScope(_owningChildEdit.Handle); if (hdc.IsNull) { return(false); } // Add the width of the character at that position. return(Gdi32.GetTextExtentPoint32W(hdc, item.ToString(), 1, ref size).IsTrue()); }
/// <summary>Rounds the region of the control.</summary> /// <param name="form">The form control to round.</param> /// <param name="rounding">The amount of rounding.</param> public static void RoundRegion(Form form, int rounding) { try { form.FormBorderStyle = FormBorderStyle.None; form.Region = Region.FromHrgn(Gdi32.CreateRoundRectRgn(0, 0, form.Width, form.Height, rounding, rounding)); } catch (Exception e) { Console.WriteLine(e); throw; } }