Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c# - How to convert IntPtr to Cursor or SafeHandle?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...