public static IntPtr ExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOGBRUSH lplb, int dwStyleCount, int[] lpStyle) { IntPtr hPen = System.Internal.HandleCollector.Add(IntExtCreatePen(fnStyle, dwWidth, lplb, dwStyleCount, lpStyle), IntSafeNativeMethods.CommonHandles.GDI); DbgUtil.AssertWin32(hPen != IntPtr.Zero, "IntExtCreatePen(style={0}, width={1}, brush={2}, styleCount={3}, styles={4}) failed.", fnStyle, dwWidth, lplb, dwStyleCount, lpStyle); return(hPen); }
public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) { IntPtr hRgn = System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), CommonHandles.GDI); DbgUtil.AssertWin32(hRgn != IntPtr.Zero, "IntCreateRectRgn([x1={0}, y1={1}, x2={2}, y2={3}]) failed.", x1, y1, x2, y2); return(hRgn); }
public static IntPtr CreatePen(int fnStyle, int nWidth, int crColor) { IntPtr hPen = System.Internal.HandleCollector.Add(IntCreatePen(fnStyle, nWidth, crColor), IntSafeNativeMethods.CommonHandles.GDI); DbgUtil.AssertWin32(hPen != IntPtr.Zero, "IntCreatePen(style={0}, width={1}, color=[{2}]) failed.", fnStyle, nWidth, crColor); return(hPen); }
public static IntPtr CreateSolidBrush(int crColor) { IntPtr hBrush = System.Internal.HandleCollector.Add(IntCreateSolidBrush(crColor), IntSafeNativeMethods.CommonHandles.GDI); DbgUtil.AssertWin32(hBrush != IntPtr.Zero, "IntCreateSolidBrush(color={0}) failed.", crColor); return(hBrush); }
/// <summary> /// Saves the current state of the device context by copying data describing selected objects and graphic /// modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a /// context stack. /// The SaveDC function can be used any number of times to save any number of instances of the DC state. /// A saved state can be restored by using the RestoreHdc method. /// See MSDN for more details. /// </summary> public int SaveHdc() { HandleRef hdc = new HandleRef(this, _hDC); int state = Interop.Gdi32.SaveDC(hdc); if (_contextStack == null) { _contextStack = new Stack(); } GraphicsState g = new GraphicsState(); g.hBitmap = _hCurrentBmp; g.hBrush = _hCurrentBrush; g.hPen = _hCurrentPen; g.hFont = _hCurrentFont; _contextStack.Push(g); #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked ((int)_hDC)))); #endif return(state); }
/// <summary> /// Restores the device context to the specified state. The DC is restored by popping state information off a /// stack created by earlier calls to the SaveHdc function. /// The stack can contain the state information for several instances of the DC. If the state specified by the /// specified parameter is not at the top of the stack, RestoreDC deletes all state information between the top /// of the stack and the specified instance. /// Specifies the saved state to be restored. If this parameter is positive, nSavedDC represents a specific /// instance of the state to be restored. If this parameter is negative, nSavedDC represents an instance relative /// to the current state. For example, -1 restores the most recently saved state. /// See MSDN for more info. /// </summary> public void RestoreHdc() { #if TRACK_HDC bool result = #endif // Note: Don't use the Hdc property here, it would force handle creation. Interop.Gdi32.RestoreDC(new HandleRef(this, _hDC), -1); #if TRACK_HDC // Note: Winforms may call this method during app exit at which point the DC may have been finalized already causing this assert to popup. Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked ((int)_hDC), restoreState))); #endif Debug.Assert(_contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()"); if (_contextStack != null) { GraphicsState g = (GraphicsState)_contextStack.Pop() !; _hCurrentBmp = g.hBitmap; _hCurrentBrush = g.hBrush; _hCurrentPen = g.hPen; _hCurrentFont = g.hFont; } #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 }
internal void Dispose(bool disposing) { if (_dc != null) { DbgUtil.AssertFinalization(this, disposing); try { // Restore original dc. _dc.RestoreHdc(); if (_disposeDc) { _dc.Dispose(disposing); } if (_graphics != null) // if created from a Graphics object... { _graphics.ReleaseHdcInternal(_dc.Hdc); _graphics = null; } } catch (Exception ex) when(!ClientUtils.IsSecurityOrCriticalException(ex)) { Debug.Fail("Exception thrown during disposing: \r\n" + ex.ToString()); } finally { _dc = null !; } } }
public static bool DeleteObject(HandleRef hObject) { System.Internal.HandleCollector.Remove((IntPtr)hObject, IntSafeNativeMethods.CommonHandles.GDI); bool retVal = IntDeleteObject(hObject); DbgUtil.AssertWin32(retVal, "DeleteObject(hObj=[0x{0:X8}]) failed.", hObject.Handle); return(retVal); }
public static int GetTextExtentPoint32(HandleRef hDC, string text, [In, Out] IntNativeMethods.SIZE size) { int byteCount = text.Length; int retVal = GetTextExtentPoint32W(hDC, text, text.Length, size); DbgUtil.AssertWin32(retVal != 0, "GetTextExtentPoint32(hdc=[0x{0:X8}], text=[{1}], size=[{2}] failed.", hDC.Handle, text, size); return(retVal); }
public static IntPtr GetCurrentObject(HandleRef hDC, int uObjectType) { IntPtr hGdiObj = IntGetCurrentObject(hDC, uObjectType); // If the selected object is a region the return value is HGI_ERROR on failure. DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetObject(hdc=[0x{0:X8}], type=[{1}]) failed.", hDC, uObjectType); return(hGdiObj); }
public static bool DeleteHDC(HandleRef hDC) { System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.HDC); bool retVal = IntDeleteDC(hDC); DbgUtil.AssertWin32(retVal, "DeleteHDC([hdc=0x{0:X8}]) failed.", hDC.Handle); return(retVal); }
/// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.Dispose1"]/*' /> internal void Dispose(bool disposing) { if (_disposed) { return; } if (Disposing != null) { Disposing(this, EventArgs.Empty); } _disposed = true; switch (_dcType) { 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)_hDC)))); #endif IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, _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)_hDC)))); #endif IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, _hDC)); _hDC = IntPtr.Zero; break; // case DeviceContextType.Metafile: - not yet supported. 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); }
public static void AssertWin32(bool expression, string message) { #if DEBUG if (!expression) { Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr()); } #endif }
[Conditional("DEBUG")] // This code will be compiled into the assembly anyways, it is up to the compiler to ignore the call. private static void AssertWin32Impl(bool expression, string format, object[] args) { #if DEBUG if (!expression) { string message = string.Format(CultureInfo.CurrentCulture, format, args); Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr()); } #endif }
/// <summary> /// Constructor to construct a DeviceContext object from an existing Win32 device context handle. /// </summary> private DeviceContext(IntPtr hDC, DeviceContextType dcType) { _hDC = hDC; _dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr($"DeviceContext(hDC=0x{(int)hDC:X8}, Type={dcType})")); #endif }
/// <summary> /// Constructor to construct a DeviceContext object from an window handle. /// </summary> private DeviceContext(IntPtr hWnd) { _hWnd = hWnd; _dcType = DeviceContextType.Display; DeviceContexts.AddDeviceContext(this); // the hDc will be created on demand. #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("DeviceContext( hWnd=0x{0:x8} )", unchecked ((int)hWnd)))); #endif }
///<summary> /// If the object was created from a DC, this object doesn't 'own' the dc so we just ignore this call. ///</summary> void IDeviceContext.ReleaseHdc() { if (_hDC != IntPtr.Zero && _dcType == DeviceContextType.Display) { #if TRACK_HDC int retVal = #endif IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, _hWnd), new HandleRef(this, _hDC)); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked ((int)_hDC), unchecked ((int)_hWnd)))); #endif _hDC = IntPtr.Zero; } }
/// <summary> /// Constructor to construct a DeviceContext object from an existing Win32 device context handle. /// </summary> private DeviceContext(IntPtr hDC, DeviceContextType dcType) { _hDC = hDC; _dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); if (dcType == DeviceContextType.Display) { _hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, _hDC)); } #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked ((int)hDC), dcType))); #endif }
/// <summary> /// Constructor to construct a DeviceContext object from an existing Win32 device context handle. /// </summary> private DeviceContext(IntPtr hDC, DeviceContextType dcType) { _hDC = hDC; _dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); if (dcType == DeviceContextType.Display) { _hWnd = Interop.User32.WindowFromDC(new HandleRef(this, _hDC)); } #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr($"DeviceContext(hDC=0x{(int)hDC:X8}, Type={dcType})")); #endif }
/// <summary> /// Explicit interface method implementation to hide them a bit for usability reasons so the object is seen as /// a wrapper around an hdc that is always available, and for performance reasons since it caches the hdc if /// used in this way. /// </summary> IntPtr IDeviceContext.GetHdc() { if (_hDC == IntPtr.Zero) { Debug.Assert(_dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device."); // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. // For example, the default font is System. _hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, _hWnd)); #if TRACK_HDC Debug.WriteLine(DbgUtil.StackTraceToStr(string.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked ((int)_hDC), unchecked ((int)_hWnd)))); #endif } return(_hDC); }
public static bool Arc( HandleRef hDC, int nLeftRect, // x-coord of rectangle's upper-left corner int nTopRect, // y-coord of rectangle's upper-left corner int nRightRect, // x-coord of rectangle's lower-right corner int nBottomRect, // y-coord of rectangle's lower-right corner int nXStartArc, // x-coord of first radial ending point int nYStartArc, // y-coord of first radial ending point int nXEndArc, // x-coord of second radial ending point int nYEndArc // y-coord of second radial ending point ) { bool retVal = IntArc(hDC, nLeftRect, nTopRect, nRightRect, nBottomRect, nXStartArc, nYStartArc, nXEndArc, nYEndArc); DbgUtil.AssertWin32(retVal, "Arc(hdc=[0x{0:X8}], ...) failed.", hDC.Handle); return(retVal); }
public void Dispose(bool disposing) { if (_nativeHandle != IntPtr.Zero) { DbgUtil.AssertFinalization(this, disposing); if (_ownHandle) { IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, _nativeHandle)); } _nativeHandle = IntPtr.Zero; if (disposing) { GC.SuppressFinalize(this); } } }
public static int GetTextMetrics(HandleRef hDC, ref IntNativeMethods.TEXTMETRIC lptm) { int retVal; if (Marshal.SystemDefaultCharSize == 1) { // ANSI IntNativeMethods.TEXTMETRICA lptmA = new IntNativeMethods.TEXTMETRICA(); retVal = IntUnsafeNativeMethods.GetTextMetricsA(hDC, ref lptmA); lptm.tmHeight = lptmA.tmHeight; lptm.tmAscent = lptmA.tmAscent; lptm.tmDescent = lptmA.tmDescent; lptm.tmInternalLeading = lptmA.tmInternalLeading; lptm.tmExternalLeading = lptmA.tmExternalLeading; lptm.tmAveCharWidth = lptmA.tmAveCharWidth; lptm.tmMaxCharWidth = lptmA.tmMaxCharWidth; lptm.tmWeight = lptmA.tmWeight; lptm.tmOverhang = lptmA.tmOverhang; lptm.tmDigitizedAspectX = lptmA.tmDigitizedAspectX; lptm.tmDigitizedAspectY = lptmA.tmDigitizedAspectY; lptm.tmFirstChar = (char)lptmA.tmFirstChar; lptm.tmLastChar = (char)lptmA.tmLastChar; lptm.tmDefaultChar = (char)lptmA.tmDefaultChar; lptm.tmBreakChar = (char)lptmA.tmBreakChar; lptm.tmItalic = lptmA.tmItalic; lptm.tmUnderlined = lptmA.tmUnderlined; lptm.tmStruckOut = lptmA.tmStruckOut; lptm.tmPitchAndFamily = lptmA.tmPitchAndFamily; lptm.tmCharSet = lptmA.tmCharSet; } else { // Unicode retVal = IntUnsafeNativeMethods.GetTextMetricsW(hDC, ref lptm); } DbgUtil.AssertWin32(retVal != 0, "GetTextMetrics(hdc=[0x{0:X8}], [out TEXTMETRIC] failed.", hDC.Handle); return(retVal); }
internal void Dispose(bool disposing) { if (_disposed) { return; } Disposing?.Invoke(this, EventArgs.Empty); _disposed = true; switch (_dcType) { 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: Interop.Gdi32.DeleteDC(new HandleRef(this, _hDC)); _hDC = IntPtr.Zero; break; case DeviceContextType.Memory: Interop.Gdi32.DeleteDC(new HandleRef(this, _hDC)); _hDC = IntPtr.Zero; break; // case DeviceContextType.Metafile: - not yet supported. 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); }
public static int GetTextExtentPoint32(HandleRef hDC, string text, [In, Out] IntNativeMethods.SIZE size) { int retVal; int byteCount = text.Length; if (Marshal.SystemDefaultCharSize == 1) { // Convert Unicode string to ANSI. byteCount = IntUnsafeNativeMethods.WideCharToMultiByte(IntNativeMethods.CP_ACP, 0, text, text.Length, null, 0, IntPtr.Zero, IntPtr.Zero); byte[] textBytes = new byte[byteCount]; IntUnsafeNativeMethods.WideCharToMultiByte(IntNativeMethods.CP_ACP, 0, text, text.Length, textBytes, textBytes.Length, IntPtr.Zero, IntPtr.Zero); // Security: Windows 95/98/Me: This value may not exceed 8192. byteCount = Math.Min(text.Length, IntNativeMethods.MaxTextLengthInWin9x); retVal = GetTextExtentPoint32A(hDC, textBytes, byteCount, size); } else { retVal = GetTextExtentPoint32W(hDC, text, text.Length, size); } DbgUtil.AssertWin32(retVal != 0, "GetTextExtentPoint32(hdc=[0x{0:X8}], text=[{1}], size=[{2}] failed.", hDC.Handle, text, size); return(retVal); }
/// <devdoc> /// Returns information about the top stack frames in a string format. The input param determines the number of /// frames to include. /// </devdoc> public static string StackFramesToStr(int maxFrameCount) { string trace = String.Empty; try { StackTrace st = new StackTrace(true); int dbgUtilFrameCount = 0; // // Ignore frames for methods on this library. // Note: The stack frame holds the latest frame at index 0. // while (dbgUtilFrameCount < st.FrameCount) { StackFrame sf = st.GetFrame(dbgUtilFrameCount); if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil)) { break; } dbgUtilFrameCount++; } maxFrameCount += dbgUtilFrameCount; // add ignored frames. if (maxFrameCount > st.FrameCount) { maxFrameCount = st.FrameCount; } for (int i = dbgUtilFrameCount; i < maxFrameCount; i++) { StackFrame sf = st.GetFrame(i); if (sf == null) { continue; } MethodBase mi = sf.GetMethod(); if (mi == null) { continue; } string args = String.Empty; string fileName = sf.GetFileName(); int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\'); if (backSlashIndex != -1) { fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1); } foreach (ParameterInfo pi in mi.GetParameters()) { args += pi.ParameterType.Name + ", "; } if (args.Length > 0) // remove last comma. { args = args.Substring(0, args.Length - 2); } trace += String.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args); } } catch (Exception ex) { if (DbgUtil.IsCriticalException(ex)) { throw; //rethrow critical exception. } trace += ex.ToString(); } return(trace.ToString()); }
/// <devdoc> /// Returns information about the top stack frames in a string format. The input param determines the number of /// frames to include. The 'message' parameter is used as the header of the returned string. /// </devdoc> public static string StackTraceToStr(string message, int frameCount) { return(String.Format(CultureInfo.CurrentCulture, "{0}\r\nTop Stack Trace:\r\n{1}", message, DbgUtil.StackFramesToStr(frameCount))); }
public static int SetGraphicsMode(HandleRef hDC, int iMode) { iMode = IntSetGraphicsMode(hDC, iMode); DbgUtil.AssertWin32(iMode != 0, "SetGraphicsMode([hdc=0x{0:X8}], [GM_ADVANCED]) failed.", hDC.Handle); return(iMode); }
public static IntNativeMethods.RegionFlags SelectClipRgn(HandleRef hDC, HandleRef hRgn) { IntNativeMethods.RegionFlags result = IntSelectClipRgn(hDC, hRgn); DbgUtil.AssertWin32(result != IntNativeMethods.RegionFlags.ERROR, "SelectClipRgn([hdc=0x{0:X8}], [hRegion=0x{1:X8}]) failed.", hDC.Handle, hRgn.Handle); return(result); }
public static IntNativeMethods.RegionFlags GetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect) { IntNativeMethods.RegionFlags result = IntGetRgnBox(hRgn, ref clipRect); DbgUtil.AssertWin32(result != IntNativeMethods.RegionFlags.ERROR, "GetRgnBox([hRegion=0x{0:X8}], [out rect]) failed.", hRgn.Handle); return(result); }