Search code examples
c#resourcescursor

C# Embed Custom Cursor


I've spent ages working on this and I've almost got it. However, there is one final problem I am suffering from and it's really starting to get under my skin. I can't embed my custom cursor into my application...

I'm currently using the following method to change the cursor to the custom one I have in the solution explorer. It's "MyCursor.cur", it's an embedded resource and I have set Copy to Output Directory to Copy if Newer. This is the code I'm using to set the cursor:

public static Cursor ActuallyLoadCursor(String path)
{
    return new Cursor(LoadCursorFromFile(path));
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr LoadCursorFromFile(string fileName);

and in my form's constructor:

Cursor = ActuallyLoadCursor("MyCursor.cur");

This is the only thing that has worked for me to load the cursor and use it in my application. This, however, copies the cursor to the same folder as the program. I have searched online for hours with no luck. Is there any way I can do this without it being copied and without a thousand lines of unnecessary code?

Here's other solutions I have tried which have failed for me:

using (MemoryStream ms = new MemoryStream(Properties.Resources.MyCursor))
{
    Cursor = new Cursor(ms);
}

Cursor = new Cursor(Assembly.GetExecutingAssembly().GetManifestResourceStream("My_Namespace.MyCursor.cur"));

These resulted in:

Image format is not valid. The image file may be corrupted. Parameter name: stream


Solution

  • Are you sure that your cursor is the right format? Is it a plain 32x32, 1-bit non-animated cursor (created, for example, with the cursor editor in Visual Studio)? According to the documentation the Cursor class only supports the most basic cursor format - animated / color cursors can only be loaded using the Windows API.

    I'm asking because I just created a new Windows Form project in VS 2012, added a new cursor, added the cursor to the resources and then used this code:

    Cursor oC;
    
    using ( MemoryStream oMS = new MemoryStream ( Properties.Resources.Cursor1 ) )
    {
        oC = new Cursor ( oMS );
    
        this.Cursor = oC;
    }
    

    This works just fine - no errors. (this is the form in the code above.)

    If your cursor is colored you can still embed it as a resource but you'll have to save it to disk first before loading it using LoadCursorFromFile. Don't save the cursor next to your executable - if it's not running from a user's profile folder, you may not have the necessary privileges to create a new file in that folder. Generate a temporary file name in the user's temporary folder (using Path.GetTempFileName) and save the cursor data there - once the cursor is loaded, you can delete the file.