C# 自定义鼠标形状

核心代码

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

namespace Dabaoku
{
	class CursorGenerator
	{
		[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 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);
		}

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

调用

Bitmap bitmap = new Bitmap(@"resource\hand.png");

control.Cursor = CursorGenerator.CreateCursor(bitmap, 3, 3);

C# Tutorial - How To Use Custom Cursors

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 theCursor 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 areGetIconInfo 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 newIconInfo struct, which we are going to populate with the icon info. We do this by calling the native methodGetIconInfo. 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(14025);
Graphics g = Graphics.FromImage(bitmap);
using (Font f = new Font(FontFamily.GenericSansSerif10))
  g.DrawString("{ } Switch On The Code", f, Brushes.Green00);

myControl.Cursor = CreateCursor(bitmap, 33);

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(14025);
      Graphics g = Graphics.FromImage(bitmap);
      using (Font f = new Font(FontFamily.GenericSansSerif10))
        g.DrawString("{ } Switch On The Code", f, Brushes.Green00);

      this.Cursor = CreateCursor(bitmap, 33);

      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.

posted on 2011-05-12 10:22  大宝pku  阅读(2649)  评论(0编辑  收藏  举报

导航