如何从 IntPtr 句柄创建 WPF 光标 [英] How to create a WPF Cursor from an IntPtr handle
问题描述
假设我有一个游标句柄,并且我想使用该句柄创建一个 WPF Cursor 实例.
Assuming I have handle of a cursor and I'd like to create an instance of WPF Cursor using that handle.
在 Windows 窗体中,System.Windows.Forms.Cursor 类有一个接受 IntPtr 的构造函数,但 WPF System.Windows.Input.Cursor 没有有一个接受 IntPtr 的构造函数.知道如何解决这个问题并从 IntPtr 句柄创建 WPF 光标吗?
In Windows Forms, System.Windows.Forms.Cursor class has a constructor which accepts IntPtr, but WPF System.Windows.Input.Cursor doesn't have a constructor that accepts IntPtr. Any idea how to get around this and create a WPF Cursor from IntPtr handle?
例如,以下代码段(从这篇文章中借用)适用于 Windows 窗体,但我会喜欢在 WPF 中编写等价物:
For example, the following piece of code (borrowed from this post)works in Windows Forms, but I'd like to write the equivalent in WPF:
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("user32.dll")]
private static extern IntPtr LoadCursor(IntPtr hInstance, UInt16 lpCursorName);
private void button1_Click(object sender, EventArgs e)
{
var l = LoadLibrary("ole32.dll");
var h = LoadCursor(l, 6);
this.Cursor = new Cursor(h);
}
推荐答案
您需要使用 CursorInteropHelper.Create(SafeHandle) 接受 SafeHandle,然后你可以像这样使用它:
You need to use CursorInteropHelper.Create(SafeHandle) which accepts a SafeHandle, then you can use it like this:
CursorInteropHelper.Create(theSafeHandle);
因此您需要使用 IntPtr
创建一个 SafeHandle
实例.但是,现在的问题是 SafeHandle 类是抽象的!由于 Microsoft.Win32.SafeHandles 命名空间 用于游标句柄,您可以通过从 SafeHandleZeroOrMinusOneIsInvalid 类:
So you need to create an instance of SafeHandle
using an IntPtr
. But, now the problem is the SafeHandle class is abstract! Since there's no implementation available in Microsoft.Win32.SafeHandles namespace for cursor handle, you can create one by deriving from SafeHandleZeroOrMinusOneIsInvalid class:
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
public sealed class SafeCursorHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[DllImport("user32.dll")]
private static extern bool DestroyCursor(IntPtr handle);
public SafeCursorHandle() : base(true) { }
public SafeCursorHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
return DestroyCursor(handle);
}
}
最后,将所有内容放在一个 WPF 示例中,该示例与 Windows 窗体示例执行相同的操作:
Finally, to put everything in a WPF example which does the same thing as the Windows Forms example:
//using System;
//using System.Runtime.InteropServices;
//using System.Windows;
//using System.Windows.Interop;
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("user32.dll")]
private static extern IntPtr LoadCursor(IntPtr hInstance, UInt16 lpCursorName);
private void Button_Click(object sender, RoutedEventArgs e)
{
var l = LoadLibrary("ole32.dll");
var h = LoadCursor(l, 6);
this.Cursor = CursorInteropHelper.Create(new SafeCursorHandle(h));
}
这篇关于如何从 IntPtr 句柄创建 WPF 光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!