C# Tutorial - How To Use Custom Cursors

Skill

C# Tutorial - How To Use Custom Cursors

Posted in:

Custom cursors are something that you don't need to use very often, but when you do need them, they can make a huge difference in the usability of your program. So today we are going to take a look at how to use your own custom cursors in C#/WinForms applications (don't worry, WPF aficionados, we will take care of you at a later date).

Changing the cursor on a WinForms control is extremely easy, as long as you are only trying to change it to one of the other standard cursors. To do that, all you need to do is set the Cursor property on your control to one of the cursors on the Cursors object. However, using a cursor of your own can be a little more difficult.

There are a couple ways to use your own cursors, and they all eventually create a new Cursor object. The simplest way is to just load a cursor file (you know, the ones with the ".cur" extension) that you created. The constructor for the Cursor can take a file path to do just that:

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

And you can then assign it as the cursor on any of your controls:

myControl.Cursor = myCursor;

So that is easy enough. But say you don't have a ".cur" file you want to use - maybe you are actually creating the cursor on the fly programmatically! Well, that gets a bit more difficult. This is because not everything we need is built into the wonderful world of .NET - we will need to interop in some other methods. In the end it is not a lot of code, it is just knowing what code to call.

The first thing we need to do is create the C# equivalent of the ICONINFO structure. We will need this to define information about the cursor we will be creating:

public struct IconInfo
{
  public bool fIcon;
  public int xHotspot;
  public int yHotspot;
  public IntPtr hbmMask;
  public IntPtr hbmColor;
}

We care about the first three member variables (you can read about the last two on MSDN if you would like). The first one (fIcon) defines if the icon it talks about is a cursor or just a regular icon. Set to false, it means that the icon is a cursor. The xHotspot and yHotspot define the actual "click point" of the cursor. Cursors are obviously bigger than 1x1 pixel, but there is really only one pixel that matters - the one defined by the hotspot coordinate. For instance, the hotspot of the standard pointer cursor is the tip of the pointer.

There are also two native methods that we will need references to in order to create the cursor. These are GetIconInfo and CreateIconIndirect. We pull them into out C# program using the following code:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

Now to write the cursor creation function:

public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
  IntPtr ptr = bmp.GetHicon();
  IconInfo tmp = new IconInfo();
  GetIconInfo(ptr, ref tmp);
  tmp.xHotspot = xHotSpot;
  tmp.yHotspot = yHotSpot;
  tmp.fIcon = false;
  ptr = CreateIconIndirect(ref tmp);
  return new Cursor(ptr);
}

This function takes in a bitmap that will be made into a cursor, and the hotspot for the cursor. We first create a new IconInfo struct, which we are going to populate with the icon info. We do this by calling the native method GetIconInfo. This function takes in a pointer to the icon (which we get by calling GetHicon() on the bitmap), and a reference to the IconInfo struct that we want populated with the information.

We then set the x and y hotspot coordinates the the values passed in, and we set fIcon to false (marking it as a cursor). Finally, we call CreateIconIndirect, which returns a pointer to the new cursor icon, and we use this pointer to create a new Cursor. The function CreateIconIndirect makes a copy of the icon to use as the cursor, so you don't have to worry about the bitmap that was passed in being locked or anything of that nature.
So now that we have this function, how do we use it? It is actually really simple:

Bitmap bitmap = new Bitmap(140, 25);
Graphics g = Graphics.FromImage(bitmap);
using (Font f = new Font(FontFamily.GenericSansSerif, 10))
  g.DrawString("{ } Switch On The Code", f, Brushes.Green, 0, 0);

myControl.Cursor = CreateCursor(bitmap, 3, 3);

bitmap.Dispose();

Here, we are creating a bitmap, and drawing the string "{ } Switch On The Code" on that bitmap. We pass that bitmap into the create cursor function with a hotspot of (3,3), and it spits out a new cursor, ready to use (in this case on the control myControl). And, of course, we dispose the original bitmap once the cursor is created. Here you can see a screenshot of that cursor in action:

Custom Cursor In Action

And here is all the code put together:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CursorTest
{
  public struct IconInfo
  {
    public bool fIcon;
    public int xHotspot;
    public int yHotspot;
    public IntPtr hbmMask;
    public IntPtr hbmColor;
  }

  public class CursorTest : Form
  {
    public CursorTest()
    {
      this.Text = "Cursor Test";

      Bitmap bitmap = new Bitmap(140, 25);
      Graphics g = Graphics.FromImage(bitmap);
      using (Font f = new Font(FontFamily.GenericSansSerif, 10))
        g.DrawString("{ } Switch On The Code", f, Brushes.Green, 0, 0);

      this.Cursor = CreateCursor(bitmap, 3, 3);

      bitmap.Dispose();
    }

    [DllImport("user32.dll")]
    public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

    public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
    {
      IconInfo tmp = new IconInfo();
      GetIconInfo(bmp.GetHicon(), ref tmp);
      tmp.xHotspot = xHotSpot;
      tmp.yHotspot = yHotSpot;
      tmp.fIcon = false;
      return new Cursor(CreateIconIndirect(ref tmp));
    }
  }
}

Hopefully, this code is a help to anyone out there trying to use custom cursors of their own. The possibilities are endless when you can actually create and modify your cursors on the fly! If you would like the Visual Studio project for the simple form above as a starting point, here it is. And as always, if you have any questions, feel free to leave them below.

Gil
02/27/2008 - 14:11

First of all I would like to thank you for the article, it helped me alot, you explain things very easly thus helping us learn easier.

second, from this article I didn't understand how exactly XHotSpot & YHotSpot help us, or better yet in what.
second, I'm wondering on if you can help me build this kind of a comment box or even better image box, that the user can chage it size, maybe the class used or something of this kind,
thanks in advance gil.

reply

Lof
03/04/2008 - 10:32

Very helpfull as created cursors only using GetHicon() always set the hotspot centered.
Thanks.

reply

Hiling
03/12/2008 - 04:14

This was a perfect article :-). But.. Any idea how to replace the system cursors for copy/move? It seems like the system overrides my cursor when drag-operations is being done..

reply

The Tallest
03/17/2008 - 12:46

Thats a good question, and the answer is a little more in depth than I can can do in a comment. Look for a tutorial in the near future on how to change the cursor during a Drag&Drop operation.

reply

BramBoucherie
04/15/2008 - 07:49

Hi,

I'm making a custom picturebox on which i need a custom cursor. It's to draw a square around an expanded pixel.

in constructor, I init the IconInfo once. On mousemove I only change the x and yhotspot and attach the changed cursor.

This all works as intended and really fast. For a while at least.

after a few hundred relocations of the cursor I get an "numericArgumentException in GDI+" on this line="this.Cursor = new Cursor(CreateIconIndirect(ref IconInfoCursorSquarePixel));"

I have been looken for a solution for a good amount of time but don't find anyting. I tryed reinit of the IconInfo, fixed the ref Iconinfo I cant find anything.

Please some help

Thank u

private void InitIcon()
/*executed only once on construction*/
{
  Bitmap CursorSquarePixel =
      new Bitmap(pxZoomFactor, pxZoomFactor);
  Graphics g = Graphics.FromImage(CursorSquarePixel);
  Pen pen = new Pen(Color.Gray, 1.0f);
  g.DrawRectangle(pen, 0, 0, pxZoomFactor - 1,
      pxZoomFactor - 1);
  pen.Dispose();
  g.Dispose();
           
  IconInfoCursorSquarePixel = new IconInfo();
  GetIconInfo(CursorSquarePixel.GetHicon(),
      ref IconInfoCursorSquarePixel);
  IconInfoCursorSquarePixel.fIcon = false;
           
  CursorSquarePixel.Dispose();
}


public void createCursor()
{
  int xpos = this.PointToClient(MousePosition).X;
  int ypos = this.PointToClient(MousePosition).Y;

  try
  {
    //put offset so that bitmap jumps per expanded pixel
    IconInfoCursorSquarePixel.xHotspot =
        xpos % pxZoomFactor;
    IconInfoCursorSquarePixel.yHotspot =
        ypos % pxZoomFactor;

    this.Cursor = new Cursor(CreateIconIndirect(
        ref IconInfoCursorSquarePixel));
  }
  catch (Exception)
  {
    Console.WriteLine("error");
  }
}

reply

Tsigabu
04/29/2008 - 02:44

It is really interesting code(note). I got many interesting things in it. So carry on providing us with such interesting and usefull notes.

reply

C
06/06/2008 - 12:59

This example was quite helpful to me, thank you for posting it. I'm wondering if once you have your cursor created, if you can then save that cursor with the ".cur" extension thus giving you the actual cursor to use in say other projects without having to programmatically create it every time? Thanks!!!

reply

Mike
07/11/2008 - 11:52

Useful note. A couple of possible resource leaks:

The documentation for the GetIconInfo() says the user must destroy the two bitmaps it creates. Also the Cursor class will not dispose of the handle passed to its constructor when the instance is destroyed.

Now if I could just work out why the text in the cursor is blurry on my machine...

reply

Eric
10/16/2008 - 12:54

Very nice article.

The text is also blurry on my machine... any ideas?

reply

Raymond
11/02/2008 - 04:47

[DllImport("user32.dll")]
public static extern IntPtr CreateIconIndirect(
ref IconInfo icon);

When calling CreateIconIndirect in Vista x64, it does not work but no problem in x86. It the above declaration works in x64?

Any x64 expert please help me. Thanks.

reply

Steph
11/11/2008 - 11:25

THANKS A LOT for this nice article!!!!!!

reply

MarLoe
01/08/2009 - 10:18

Another way is to include the “myCursor.cur” file in the resources.resx. (Right-click “resources.resx” in your project under “Properties”, and select “View Designer”. Select the “Files” view, and drag the “myCursor.cur” file in here).

After that, you can load the cursor through a stream (one line of code):

Cursor = new Cursor(new System.IO.MemoryStream(
    TheProject.Properties.Resources.mouse));

reply

Robert Lloyd
05/07/2009 - 14:59

Thanks a ton for this. You'd think this would be documented somewhere....

reply

Aerdanel
03/24/2009 - 07:25

Very nice article, it was precisely what I was looking for !

But I found a little problem... It seems there is some memory leak when calling GetIconInfo, hbmMask and hbmColors aren't destroyed automatically..

I tried to use DeleteObject :

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr handle);

but it didn't change anything... Any idea ?

reply

Aerdanel
03/24/2009 - 10:42

Here's a function to correct memory leaks :

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr handle);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

public static IntPtr pointeurCurseur;

public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
{
        if (pointeurCurseur != IntPtr.Zero) DestroyIcon(pointeurCurseur);

        IntPtr ptr = bmp.GetHicon();
        IconInfo tmp = new IconInfo();
        GetIconInfo(ptr, ref tmp);
        tmp.xHotspot = xHotSpot;
        tmp.yHotspot = yHotSpot;
        tmp.fIcon = false;
        pointeurCurseur = CreateIconIndirect(ref tmp);

        if (tmp.hbmColor != IntPtr.Zero) DeleteObject(tmp.hbmColor);
        if (tmp.hbmMask != IntPtr.Zero) DeleteObject(tmp.hbmMask);
        if (ptr != IntPtr.Zero) DestroyIcon(ptr);

        return new Cursor(pointeurCurseur);
}

reply

trod999
04/29/2009 - 16:31

Aerdanel, thanks a ton!

I'd like to add that not only does your function cure memory leaks, it makes the program rock solid as well.

As a "stress test" of this function, I added a MouseMove() event handler to the form, and then incremented a local integer, and then used that integer in a .ToString() method to make a cursor. 1243 cursors and the program dies every time. With your additions I was well over 50,000 cursors, and it was running just fine.

Thanks again.

-- Pete

reply

Dan
05/12/2009 - 17:32

Hi,

Million Thanks!
Exactly what I needed!

I'm happy to contribute my improvements:
1) I drew my custom bitmap file, and made the White color transparent.
2) I made a private generic method and 2 calling methods, in a separate utility class.
I think this is the correct object-oriented approach.
3) I discovered that you can multiply the size of the BMP file I have.
4) I too used the image file that is embedded in the project resource file. This way the BMP files are not used in the installation or production directory. Goto the prohect's resource file, Images->Add->Use existing file, add the file, then save the resx file. Then the file name is available in the Resourcers class, see my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

namespace NS
{
    public static class CursorUtils
    {
       
        private struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

        [DllImport("user32.dll")]
        private static extern IntPtr CreateIconIndirect(ref IconInfo icon);

        internal static Cursor getDefaultCursor()
        {
            Cursor cursor =
                CreateCursor(Properties.Resources.YellowBigArrow, 0, 0);

            return cursor;
        }

        internal static Cursor getWaitCursor()
        {
            Cursor cursor =
                CreateCursor(Properties.Resources.YellowBigArrowPleaseWait, 0, 0);

            return cursor;
        }

        public static IntPtr pointeurCurseur;

        public static Cursor CreateCursor(Bitmap bmp_parm, int xHotSpot, int yHotSpot)
        {
            Image img = bmp_parm;
            Bitmap bmp = new Bitmap(img, new Size(img.Width * 1, img.Height * 1));
            bmp.MakeTransparent(Color.White);

            if (pointeurCurseur != IntPtr.Zero) DestroyIcon(pointeurCurseur);

            IntPtr ptr = bmp.GetHicon();
            IconInfo tmp = new IconInfo();
            GetIconInfo(ptr, ref tmp);
            tmp.xHotspot = xHotSpot;
            tmp.yHotspot = yHotSpot;
            tmp.fIcon = false;
            pointeurCurseur = CreateIconIndirect(ref tmp);

            if (tmp.hbmColor != IntPtr.Zero) DeleteObject(tmp.hbmColor);
            if (tmp.hbmMask != IntPtr.Zero) DeleteObject(tmp.hbmMask);
            if (ptr != IntPtr.Zero) DestroyIcon(ptr);

            return new Cursor(pointeurCurseur);
        }


        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr handle);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        extern static bool DestroyIcon(IntPtr handle);


    }

}

reply

Anonymous
01/26/2010 - 03:51

so, I found it earlier, but the problem is probably the same ...

"System.ArgumentException: Win32 handle passed to Cursor is not valid or is the wrong type.
at System.Windows.Forms.Cursor ..ctor(IntPtr handle)"
at CreateCursor(...

Qould You check this? Please

My Code.

   [DllImport("user32.dll", CharSet = CharSet.Auto)]
        extern static bool DestroyIcon(IntPtr handle);

        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr handle);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

        [DllImport("user32.dll")]
        public static extern IntPtr CreateIconIndirect(ref IconInfo icon);

        public static IntPtr pointeurCurseur;

        public struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

   public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
        {
            if (pointeurCurseur != IntPtr.Zero)
            {
                DestroyIcon(pointeurCurseur);
            }

            IntPtr ptr = bmp.GetHicon();
            IconInfo tmp = new IconInfo();
            GetIconInfo(ptr, ref tmp);
            tmp.xHotspot = xHotSpot;
            tmp.yHotspot = yHotSpot;
            tmp.fIcon = false;
            pointeurCurseur = CreateIconIndirect(ref tmp);

            if (tmp.hbmColor != IntPtr.Zero)
            {
                DeleteObject(tmp.hbmColor);
            }
            if (tmp.hbmMask != IntPtr.Zero)
            {
                DeleteObject(tmp.hbmMask);
            }
            if (ptr != IntPtr.Zero)
            {
                DestroyIcon(ptr);
            }

         
                return new Cursor(pointeurCurseur);  //<-----------error here
           
        }



        private void changeCursor(int type)
        {
            int _cursorSizePx = Convert.ToInt32(((200.0 * _cursorSize) / _calibration));//px

            Bitmap b = new Bitmap(_cursorSizePx + 1, _cursorSizePx + 1);
            Graphics g = Graphics.FromImage(b);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            switch (type)
            {
                case 0:

                    g.FillEllipse(new SolidBrush(_cursorColor), 0, 0, _cursorSizePx, _cursorSizePx);
                    break;
                case 1:
                    g.DrawEllipse(new Pen(new SolidBrush(_figureColor), 3), 1, 1, _cursorSizePx - 3, _cursorSizePx - 3);
                    g.FillEllipse(new SolidBrush(_sqreenColor), 1, 1, _cursorSizePx - 3, _cursorSizePx - 3);
                    break;
            }

            IntPtr ptr = b.GetHicon();

            Cursor c = CreateCursor(b, _cursorSizePx / 2, _cursorSizePx / 2);

            this.Cursor = c;
            b.Dispose();
        }

reply

Anonymous
01/26/2010 - 07:38

sorry. I left this* line of code, and this was a problem :)

//*
IntPtr ptr = b.GetHicon();

reply

Dan
05/12/2009 - 17:35

Question -

The custom cursor works great with this code.

But - When I use MessageBox.Show the cursor returns to the default WinForms arrow cursor until the user messagebox is closed, and then returns to my custom cursor.

How to solve it?

P.S. the solution works on .Net 3.5.

reply

The Tallest
05/13/2009 - 08:23

Did you pass in your current window as the "owner" parameter to MessageBox.Show? That might get it to work.

reply

Dan
05/13/2009 - 09:39

Hi "The Tallest",

I'm tall myself -:)

Thanks for your reply.
I call MessageBox.Show from user controls inside my main form. In each user-control I use MessageBox.Show(this, ...).
The user control belongs to the Controls collection of a Panel that belongs to the controls collection of the main Form.

Therefore the "this" in the call is the user control, not the main Form.
Is there a difference?

Thanks!

reply

The Tallest
05/13/2009 - 15:51

There shouldn't be a difference. If thats not working, then I'm not sure how to get it to work - I'm betting the message box is setting the cursor back to the standard one. Your two choices probably are to either figure out how to set the cursor specifically on the MessageBox (which I'm not sure how to do), or roll your own message box (which should be pretty easy).

reply

Dan
05/13/2009 - 17:00

Thanks tallest.

1) Can you suggest how to implement a MessageBox?
I use the Telerik RadMessageBox which is very nice.
Check their website, they have great WPF-like controls for Windows Forms with 5 cool themes out of the box,
I prefer to use them.

2) The Messagebox class exposes almost no properties or methods - how to change its behavior?

Thanks for your replies.

reply

Rodrigo Santos
11/05/2009 - 14:14

Hello guys!

Im dealing with memory leak problems on this code of create custom cursors.

The difference of this code to my code is that my cursor is dynamically generated. Using graphics and others bitmaps.

Should i call dispose on every objects of System.Drawing? because im still getting memory leak problems, even with the Aerdanel solution.

Thanks for your help :)

reply

Dan
01/05/2010 - 16:33

Great article. However, is there a way to still make the default cursor available, with the newly created bitmap appearing underneath the arrow?

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors