C# 自定义鼠标光标(位图+颜色+大小)
用户可自定义位图,自定义颜色,自定义光标大小
1.包含的命名空间:
using System.Runtime.InteropServices;using System.Windows.Forms;using System.Drawing;
2.类定义
class CursorUserDefine{[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, Color corlor, int xHotSpot, int yHotSpot){//光标颜色设置for (int i = 0; i < bmp.Height; ++i){for (int j = 0; j < bmp.Width; ++j){bmp.SetPixel(j, i, Color.FromArgb(corlor.R, corlor.G, corlor.B));}}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;}}
3.调用
//变量定义int nWidth = 5;//设定位图大小int nHeight = 5;int xHotSpot = 5;//设定光标大小int yHotSpot = 5;Bitmap bmp = new Bitmap(Image.FromFile("image.bmp")); // 加载图像Color color_choose = Color.Black;//设定光标位图颜色//在需要设置鼠标光标的位置调用下面函数即可,注意调用前根据需要更新位图、大小、颜色。this.Cursor = CursorUserDefine.CreateCursor(new Bitmap(bmp,new Size(nWidth, nHeight)), color_choose, xHotSpot, yHotSpot);