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

RegionScope

struct RegionScope
Helper to scope creating regions. Deletes the region when disposed.
using System.Drawing; using System.Runtime.CompilerServices; namespace Windows.Win32.Graphics.Gdi { [CompilerFeatureRequired("RefStructs")] internal ref struct RegionScope { public HRGN Region { [IsReadOnly] get; private set; } public bool IsNull { [IsReadOnly] get { return Region.IsNull; } } public RegionScope(Rectangle rectangle) { Region = PInvokeCore.CreateRectRgn(rectangle.X, rectangle.Y, rectangle.Right, rectangle.Bottom); } public RegionScope(int x1, int y1, int x2, int y2) { Region = PInvokeCore.CreateRectRgn(x1, y1, x2, y2); } public RegionScope(HDC hdc) { HRGN hRGN = PInvokeCore.CreateRectRgn(0, 0, 0, 0); if (PInvokeCore.GetClipRgn(hdc, hRGN) == 1) Region = hRGN; else { PInvokeCore.DeleteObject(hRGN); Region = default(HRGN); } } public RegionScope(HRGN region) { Region = region; } public static implicit operator HRGN(RegionScope regionScope) { return regionScope.Region; } public void RelinquishOwnership() { Region = default(HRGN); } [IsReadOnly] public void Dispose() { if (!IsNull) PInvokeCore.DeleteObject(Region); } } }