<PackageReference Include="System.Drawing.Common" Version="10.0.0-preview.1.25080.3" />

BeginPaintScope

Helper to scope lifetime of an HDC retrieved via BeginPaint
using System.Drawing; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Windows.Win32.Foundation; namespace Windows.Win32.Graphics.Gdi { [CompilerFeatureRequired("RefStructs")] internal readonly ref struct BeginPaintScope { private readonly PAINTSTRUCT _paintStruct; public HDC HDC { get; } public HWND HWND { get; } public Rectangle PaintRectangle => _paintStruct.rcPaint; public BeginPaintScope(HWND hwnd) { HDC = PInvokeCore.BeginPaint(hwnd, out _paintStruct); HWND = hwnd; } public static implicit operator HDC([In] [IsReadOnly] ref BeginPaintScope scope) { return scope.HDC; } public void Dispose() { if (!HDC.IsNull) PInvokeCore.EndPaint(HWND, ref _paintStruct); } } }