Search code examples
c#xnamonogamemouse-cursor

MonoGame Custom Realtime Cursor


So I would like to use a custom cursor from a .cur file when the mouse enters the game window. I did this with a Draw on the SpriteBatch but there is a delay between the Windows mouse and the draw which makes it uneasy.

So I did my research (of course) and I found this: Adding a custom cursor in XNA/C#?

I followed up to the second answer because I had tried the first. I followed this tutorial: http://allenwp.com/blog/2011/04/04/changing-the-windows-mouse-cursor-in-xna/

But every time I try to load the cursor I get a Win32Exception : File not found. I checked several times. The file name and directory is correct. But still the IntPtr returns 0. This is what i use to call the file:

Cursor myCursor = RealtimeCursor.LoadCustomCursor("Content\\Cursors\\cursor.cur");

And this is my RealtimeCursor class:

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;
        }
    }
}

I would love if someone was actually able to test the code on his computer and maybe find out why the User32.dll wont load my cursor file. If you need any file feel free to ask me in the comments. :) Thanks again for your help.


Solution

  • Instead of using a DllImport that will tie you to Windows, let me suggest a simpler cross-platform approach:

    1. When running on WindowsDX, use System.Windows.Forms.Cursor.Current to set a custom cursor.

    2. When running on WindowsGL, Linux or Mac, use OpenTK.NativeWindow.MouseCursor to set a custom cursor.

    You will have to reference the relevant assemblies, System.Windows.Forms or OpenTK, in your project.

    Consider making a feature request at https://github.com/mono/MonoGame/issues. This feature does not exist in XNA, but it is probably useful enough to add directly to MonoGame.