vvn
vvn

Reputation: 23

Setting custom cursor over a Windows Form in C#

I'm creating a WinForms application in Visual C#, and would like to change the cursor to a custom image (.cur) that I created. I want the cursor image to change to this over the form window only.

All previously answered questions suggest setting this.cursor to a new cursor object created with the path to the cursor, with statements like these:

this.Cursor = new Cursor(@"C:\green.cur"); // this
this.Cursor = new Cursor(GetType(), @"C:\green.cur"); // or this

but both statements result in the same error :

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

I've also tried importing the cursor with LoadImage after importing user32.dll as suggested here but this resulted in the error :

Win32 handle passed to Cursor is not valid or is the wrong type.

I'm able to set the cursor to the standard wait cursor with the following statement :

this.Cursor = Cursors.WaitCursor;

The same .cur file works perfectly when used to set the cursor in a C++ program where the cursor is embedded in a resource.

Upvotes: 2

Views: 1285

Answers (1)

Tzah Mama
Tzah Mama

Reputation: 1567

You need to use LoadCursorFromFile:

[DllImport("user32.dll")]
static extern IntPtr LoadCursorFromFile(string lpFileName);

and when you want to change your cursor:

IntPtr cursor = LoadCursorFromFile(@"C:\green.cur");
this.Cursor = new Cursor(cursor);

Upvotes: 2

Related Questions