Skip to content

Abstract DeviceContextSafeHandle with concrete DeleteDCSafeHandle and ReleaseDCSafeHandle #111

Closed

Description

@jnm2

Could CsWin32 do something like this? I like declaring Gdi32 methods to use an abstract DeviceContextSafeHandle so that not just any SafeHandle can be passed, but then I have make CreateCompatibleDC return DeleteDCSafeHandle and GetDC return ReleaseDCSafeHandle. (I call mine CreatedContextSafeHandle and WindowDeviceContextSafeHandle).

The main benefit for me is that when passing WindowDeviceContextSafeHandle around between my own methods, I know it's always valid to access the HWnd property.

public abstract class DeviceContextSafeHandle : SafeHandle
{
    protected DeviceContextSafeHandle() : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true)
    {
    }

    protected DeviceContextSafeHandle(IntPtr handle) : this()
    {
        SetHandle(handle);
    }

    public sealed override bool IsInvalid => handle == IntPtr.Zero;
}

public sealed class CreatedDeviceContextSafeHandle : DeviceContextSafeHandle
{
    private CreatedDeviceContextSafeHandle()
    {
    }

    protected override bool ReleaseHandle() => DeleteDC(handle);

    [DllImport("gdi32.dll")]
    private static extern bool DeleteDC(IntPtr hdc);
}

public sealed class WindowDeviceContextSafeHandle : Gdi32.DeviceContextSafeHandle
{
    public WindowDeviceContextSafeHandle(IntPtr hWnd, IntPtr handle) : base(handle)
    {
        HWnd = hWnd;
    }

    public IntPtr HWnd { get; }

    protected override bool ReleaseHandle() => ReleaseDC(HWnd, handle);

    [DllImport("user32.dll")]
    private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
}

Activity

  1. jnm2 commented on Feb 17, 2021

    @jnm2
    ContributorAuthor

    I've also preferred a more strongly-typed BitmapSafeHandle option so that there is some type safety for things like int GetObject(BitmapSafeHandle h, int c, out BITMAP pv);. I have it inherit from a virtual GdiObjectSafeHandle class.

  2. AArnott commented on Feb 17, 2021

    @AArnott
    Member

    Per the design in #9, we won't be taking any derived type of SafeHandle as inputs any more anyway. Only SafeHandle itself.

  3. added
    wontfix
    on Feb 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    wontfix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions