<PackageReference Include="System.Drawing.Common" Version="10.0.0-rc.2.25502.107" />

GetDcScope

struct GetDcScope
Helper to scope lifetime of an HDC retrieved via GetDC and GetDCEx. Releases the HDC (if any) when disposed.
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Windows.Win32.Foundation; namespace Windows.Win32.Graphics.Gdi { [CompilerFeatureRequired("RefStructs")] internal readonly ref struct GetDcScope { public HDC HDC { get; } public HWND HWND { get; } public static GetDcScope ScreenDC => new GetDcScope(HWND.Null); public bool IsNull => HDC.IsNull; public GetDcScope(HWND hwnd) { HWND = hwnd; HDC = PInvokeCore.GetDC(hwnd); } public GetDcScope(HWND hwnd, HRGN hrgnClip, GET_DCX_FLAGS flags) { HWND = hwnd; HDC = PInvokeCore.GetDCEx(hwnd, hrgnClip, flags); } public static implicit operator IntPtr([In] [IsReadOnly] ref GetDcScope scope) { return scope.HDC; } public static implicit operator HDC([In] [IsReadOnly] ref GetDcScope scope) { return scope.HDC; } public void Dispose() { if (!HDC.IsNull) PInvokeCore.ReleaseDC(HWND, HDC); } } }