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:

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.
Source Files:
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.
Very helpfull as created cursors only using GetHicon() always set the hotspot centered. Thanks.
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..
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.
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
It is really interesting code(note). I got many interesting things in it. So carry on providing us with such interesting and usefull notes.
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!!!
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...
Very nice article.
The text is also blurry on my machine... any ideas?
[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.
THANKS A LOT for this nice article!!!!!!
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):
Thanks a ton for this. You'd think this would be documented somewhere....
please can you explain this much more??
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 :
but it didn't change anything... Any idea ?
Here's a function to correct memory leaks :
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
thanks Aerdanel, your fix works as a charm, even in 2012 ; i spotted the GDI leak just by observing the number of GDI-objects column in the task manager
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.
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.
sorry. I left this* line of code, and this was a problem :)
//* IntPtr ptr = b.GetHicon();
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.
Did you pass in your current window as the "owner" parameter to
MessageBox.Show? That might get it to work.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!
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).
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.
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 :)
Great article. However, is there a way to still make the default cursor available, with the newly created bitmap appearing underneath the arrow?
The post helped a lot. God bless you uploader :D
Can you please explain how to apply a bitmap on iconinfo sructure it have a transparent portions of cursor ?
how to add this article in my account?
I'm using the code and after an error which I can't reproduce I only get Cursors with a size of 32x32.
Does any one know a possible solution?
Thank's
Sorry System reboot was enough!
This excellent tutorial, Is it possible to save created cursor to disk?
Is there a solution to the blurry or bold text? I have created a bitmap with an image and some text, while the image is perfect, the text always appears bold.
This is an awesome article. Thanks.