38

In a UserControl I want to change the mouse cursor from the arrow, to a hand icon.
What I currently do is this:

this.Cursor = Cursors.Hand;

This is very nice, it gives me a mouse cursor looking like this:

enter image description here

But here comes my problem... this shows a hand with a pointing finger.
What I need is a "grabbing" hand, more like this one:

enter image description here

How do I do this?, How can I load an icon file (.ico), a cursor file (.cur), or image file (.png), and use it as the mouse cursor?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Bart Gijssens
  • 1,572
  • 5
  • 20
  • 38
  • 1
    The accepted answer works if the supplied file does not have color. In the case where you have color - you need to make use of the Windows API as described in my answer below. – Derek W Mar 16 '14 at 16:29
  • @ Derek W: I did not realize that. The cursors I use indeed do not contain color info. – Bart Gijssens Apr 25 '14 at 07:00

4 Answers4

19

If you have a cursor file:

Cursor myCursor = new Cursor("myCursor.cur");
myControl.Cursor = myCursor;

otherwise you have to create one:

some more information about custom cursors

fixagon
  • 5,506
  • 22
  • 26
5

A caveat to using custom cursors with the WinForms Cursor class is that when using the stream, filename, and resource constructor overloads the supplied .cur file must be black and white in color.

Meaning that this will not work if the .cur files contains any colors besides black and white.

Cursor myCursor = new Cursor("myCursor.cur");
myControl.Cursor = myCursor;

There is a way around this limitation by using the Windows handle constructor overload:

Create the handle by using the Windows API:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr LoadCursorFromFile(string fileName);

Then pass it to the appropriate Cursor constructor like this:

IntPtr handle = LoadCursorFromFile("myCursor.cur");
Cursor myCursor = new Cursor(handle);
myControl.Cursor = myCursor;

I hope this prevents others from scratching their heads to an ArgumentException being thrown stating: Image format is not valid. The image file may be corrupted. when using the other Cursor constructor overloads with a .cur file that contains color.

Derek W
  • 9,708
  • 5
  • 58
  • 67
2

Have you tried System.Windows.Forms.Cursor curs = new System.Windows.Forms.Cursor(file_name); ?

Djole
  • 1,145
  • 5
  • 10
0

I tested this method. It's OK. This is my apply:

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern IntPtr LoadCursorFromFile(string fileName);
    Cursor myCursor;
    private void tsbtn_ZoomIn_Click(object sender, EventArgs e)
    {
        IntPtr handle = LoadCursorFromFile("view_zoom_in.cur");
        myCursor = new Cursor(handle);
        zg1.Cursor = myCursor;
    }
nult2003
  • 1
  • 1