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

CreateBitmapScope

Helper to scope lifetime of a HBITMAP created via CreateBitmap Deletes the HBITMAP (if any) when disposed.
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Windows.Win32.Graphics.Gdi { [CompilerFeatureRequired("RefStructs")] internal readonly ref struct CreateBitmapScope { public HBITMAP HBITMAP { get; } public bool IsNull => HBITMAP.IsNull; public unsafe CreateBitmapScope(int nWidth, int nHeight, uint nPlanes, uint nBitCount, void* lpvBits) { HBITMAP = PInvokeCore.CreateBitmap(nWidth, nHeight, nPlanes, nBitCount, lpvBits); } public CreateBitmapScope(HDC hdc, int cx, int cy) { HBITMAP = PInvokeCore.CreateCompatibleBitmap(hdc, cx, cy); } public static implicit operator HBITMAP([In] [IsReadOnly] ref CreateBitmapScope scope) { return scope.HBITMAP; } public static implicit operator HGDIOBJ([In] [IsReadOnly] ref CreateBitmapScope scope) { return scope.HBITMAP; } public static explicit operator IntPtr([In] [IsReadOnly] ref CreateBitmapScope scope) { return scope.HBITMAP; } public void Dispose() { if (!HBITMAP.IsNull) PInvokeCore.DeleteObject(HBITMAP); } } }