You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过IntPtr游标句柄创建WPF平台的Cursor实例?

WPF 提供了专门的互操作工具类 CursorInteropHelper 用来从游标句柄创建 System.Windows.Input.Cursor 实例,你可以通过它的静态 Create 方法实现需求,等效实现代码如下:

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr LoadLibrary(string dllToLoad);

[DllImport("user32.dll")]
private static extern IntPtr LoadCursor(IntPtr hInstance, ushort lpCursorName);

[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr hModule);

private void Button_Click(object sender, RoutedEventArgs e)
{
    IntPtr libraryHandle = LoadLibrary("ole32.dll");
    IntPtr cursorHandle = LoadCursor(libraryHandle, 6);
    // 从游标句柄创建WPF Cursor实例
    this.Cursor = CursorInteropHelper.Create(cursorHandle);
    // 释放加载的库资源
    FreeLibrary(libraryHandle);
}

额外注意事项:

  • 调用 LoadLibrary 加载的动态库使用完成后需要调用 FreeLibrary 释放,避免内存泄漏
  • 如果你的游标句柄是通过 CreateCursor、CreateIconIndirect 等API自行创建的,需要在游标不再使用后调用 DestroyCursor 释放句柄资源,避免GDI资源泄漏
  • CursorInteropHelper.Create 是WPF官方提供的Win32互操作API,兼容性和稳定性有保障,不需要额外使用反射等非常规手段实现

内容的提问来源于stack exchange,提问作者Reza Aghaei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:21:04