C#: How to load Cursor from Resource file?

I do it by adding the cursor .cur file into the Resources part of the project (I am using Visual Studio). I'm not sure if it would have to be .cur, so long as the development program can load it.

Having done that in the variables declaration part of my code I create a MemoryStream from the cursor file:

private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(myCurrentProject.Properties.Resources.myCursorFile);

...and then you can create the cursor from the MemoryStream:

private Cursor newCursor = new Cursor(cursorMemoryStream);

You can then assign the cursor as you like within the program, e.g.

pictureBox1.Cursor = newCursor;

and the new cursor is compiled as part of the program.


I haven't found any better way than dumping to a temp file and use the Win32 load cursor from file method. The hack goes something like this (I removed a big chunk of boilerplate code for clarity, in which a temp file is written with the data from the stream). Also, all exception handling etc. was removed.

[DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern IntPtr LoadCursorFromFile(String str);

public static Cursor LoadCursorFromResource(string resourceName)
{         
     Stream cursorStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);        

     // Write a temp file here with the data in cursorStream

     Cursor result = new Cursor(LoadCursorFromFile(tempFile));
     File.Delete(tempFile);

     return result.
}

You would use this as (remember namespaces when loading embedded resources).

Cursors.Current = LoadCursorFromResource("My.Namespace.Filename");

after a few turns to the issue, I find the elegant solution is:

internal static Cursor GetCursor(string cursorName)
    {
        var buffer = Properties.Resources.ResourceManager.GetObject(cursorName) as byte[];

        using (var m = new MemoryStream(buffer))
        {
            return new Cursor(m);
        }
    }

Tags:

C#

.Net