C# – When reading a Cursor from a resources file an ArgumentException is thrown

cnetwinforms

When I use a MemoryStream to load a Cursor from a resources file I receive an ArgumentException. Here is the code I use to load the cursor:

Cursor myCursor
    = new Cursor(new MemoryStream(WaterforMGC.Properties.Resources.waterspray));
Cursor = myCursor;

But I get the error. I have no idea what is wrong, I even changed Cursor = myCursor; to this.Cursor = myCursor; which gave me the same error. I tried gameform.Cursor = myCursor; but that didn't work at all.

System.ArgumentException: Image format is not valid. The image file may be corrupted.
Parameter name: stream ---> System.Runtime.InteropServices.COMException (0x800A01E1): Exception from HRESULT: 0x800A01E1 (CTL_E_INVALIDPICTURE)
   at System.Windows.Forms.UnsafeNativeMethods.IPersistStream.Load(IStream pstm)
   at System.Windows.Forms.Cursor.LoadPicture(IStream stream)
   --- End of inner exception stack trace ---
   at System.Windows.Forms.Cursor.LoadPicture(IStream stream)
   at WaterforMGC.gameform.Form1_Load(Object sender, EventArgs e) in C:\Users\Jan\Documents\Visual Studio 2008\Projects\WaterforMGC\WaterforMGC\Form1.cs:line 39
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Best Answer

The problem is spelled out on the very first line of the exception:

System.ArgumentException: Image format is not valid. The image file may be corrupted.

Are you sure the image you're loading is in an uncorrupted state, and is compatible with the image format for cursors?

The Cursor class does not support animated cursors (.ani files) or cursors with colors other than black and white.

Do you have any other places where you load a cursor image and it works? You might be able to work off of that to determine what's going wrong here.

Related Topic