Skip to main content

C# Tutorial - How To Use Custom Cursors [Intermediate]


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.

Source Files:

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as