C# 自定义鼠标光标

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);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值