自定义实时光标

本文关键字:光标 实时 自定义 | 更新日期: 2023-09-27 18:06:02

所以当鼠标进入游戏窗口时,我想使用来自.cur文件的自定义光标。我在SpriteBatch上进行了绘制,但是在Windows鼠标和绘制之间存在延迟,这让它变得不舒服。

所以我做了我的研究(当然),我发现这个:添加一个自定义光标在XNA/c# ?

我接着问第二个答案,因为我已经试过第一个答案了。我遵循这个教程:http://allenwp.com/blog/2011/04/04/changing-the-windows-mouse-cursor-in-xna/

但是每次我尝试加载光标时,我都会得到Win32Exception: File not found。我检查了好几次。文件名称和目录正确。但是IntPtr仍然返回0。这是我用来命名文件的:

Cursor myCursor = RealtimeCursor.LoadCustomCursor("Content''Cursors''cursor.cur");
这是我的RealtimeCursor类:
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Project_4
{
    static class RealtimeCursor
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr LoadCursorFromFile(string path);
        public static Cursor LoadCustomCursor(string path)
        {
            IntPtr hCurs = LoadCursorFromFile(path);
            if (hCurs == IntPtr.Zero) throw new Win32Exception();
                var curs = new Cursor(hCurs);
            // Note: force the cursor to own the handle so it gets released properly
            var fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
            fi.SetValue(curs, true);
            return curs;
        }
    }
}

如果有人真的能够在他的计算机上测试代码,也许会发现为什么User32.dll不会加载我的光标文件。如果你需要任何文件,请随时在评论中问我。:)再次感谢您的帮助。

自定义实时光标

不要使用将您绑定到Windows的DllImport,让我建议一个更简单的跨平台方法:

  1. 当在windowsx上运行时,使用System.Windows.Forms.Cursor.Current来设置自定义光标。

  2. 当在WindowsGL, Linux或Mac上运行时,使用opentk . nativewindows . mousecursor来设置自定义光标

你必须在你的项目中引用相关的程序集,System.Windows.FormsOpenTK

考虑在https://github.com/mono/MonoGame/issues上提出特性请求。此功能在XNA中不存在,但它可能足够有用,可以直接添加到MonoGame中。

有一种更简单的方法。首先添加一个对System.Windows.Forms的引用,然后在Initialize方法中添加以下代码

Form form = (Form)Form.FromHandle(this.Window.Handle);
form.Cursor = Cursors.Hand;