How to convert IntPtr to Cursor or SafeHandle?
Asked Answered
G

2

1

I'm in .NET 3.5, I have found

CursorInteropHelper.Create()

method here. However it is absolutely unclear how do I convert IntPtr for cursor to SafeHandle. The list of implementations of SafeHandle listed here does not include SafeCursorHandle and others are abstract or unrelated. Is the only way to go is to create my own implementation of SafeHandle?

Gunther answered 16/4, 2013 at 23:23 Comment(0)
C
3

SafeHandle is an abstract class. It wants you to provide an object of a concrete SafeHandle derived class that can release the handle. Unfortunately you forgot to mention how you obtained that IntPtr so we cannot know how it should be released.

I'll take a guess and assume it is a GDI cursor, the one you get from the CreateCursor() winapi function. Which requires calling DestroyCursor() to release the handle. Such a class could look like this:

class SafeCursorHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid {
    public SafeCursorHandle(IntPtr handle) : base(true) {
        base.SetHandle(handle);
    }
    protected override bool ReleaseHandle() {
        if (!this.IsInvalid) {
            if (!DestroyCursor(this.handle))
                throw new System.ComponentModel.Win32Exception();
            this.handle = IntPtr.Zero;
        }
        return true;
    }
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    private static extern bool DestroyCursor(IntPtr handle);
}

Tweak the ReleaseHandle() override as necessary to release the handle in your case.

Cleodel answered 17/4, 2013 at 2:50 Comment(0)
D
0

According to the MSDN doc, ReleaseHandle() must never fail: http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.safehandle.releasehandle%28v=vs.110%29.aspx "Because one of the functions of SafeHandle is to guarantee prevention of resource leaks, the code in your implementation of ReleaseHandle must never fail."

IMO, this means that it must not throw - just like native destructors.

Deity answered 23/4, 2014 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.