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

SelectObjectScope

Helper to scope selecting a GDI object into an HDC. Restores the original object into the HDC when disposed.
using System.Runtime.CompilerServices; namespace Windows.Win32.Graphics.Gdi { [CompilerFeatureRequired("RefStructs")] internal readonly ref struct SelectObjectScope { private readonly HDC _hdc; public HGDIOBJ PreviousObject { get; } public SelectObjectScope(HDC hdc, HGDIOBJ object) { if (object.IsNull) { _hdc = default(HDC); PreviousObject = default(HGDIOBJ); } else { _hdc = hdc; PreviousObject = PInvokeCore.SelectObject(hdc, object); } } public void Dispose() { if (!_hdc.IsNull) PInvokeCore.SelectObject(_hdc, PreviousObject); } } }