栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

解决C# winForm自定义鼠标样式的两种实现方法详解

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决C# winForm自定义鼠标样式的两种实现方法详解

第一种:(调用系统API)
首先引入两个命名空间
复制代码 代码如下:
using System.Runtime.InteropServices;
using System.Reflection;

导入API
复制代码 代码如下:
[Dllimport("user32.dll")]
public static extern IntPtr LoadCursorFromFile(string fileName);
[Dllimport("user32.dll")]
public static extern IntPtr SetCursor(IntPtr cursorHandle);
[Dllimport("user32.dll")]
 public static extern uint DestroyCursor(IntPtr cursorHandle);

接下来使用自己的鼠标样式
复制代码 代码如下:
private void Form1_Load(object sender, EventArgs e)
        {
            Cursor myCursor = new Cursor(Cursor.Current.Handle);
            IntPtr colorCursorHandle = LoadCursorFromFile("my.cur");//鼠标图标路径
              myCursor.GetType().InvokeMember("handle", BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.Instance |
            BindingFlags.SetField, null, myCursor,
            new object[] { colorCursorHandle });
            this.Cursor = myCursor;
        }

第二种:(不用API方式的,鼠标样式只需要一张背景透明的图片就行了,png或gif格式的)
复制代码 代码如下:
public void SetCursor(Bitmap cursor, Point hotPoint)
        {
            int hotX = hotPoint.X;
            int hotY = hotPoint.Y;
            Bitmap myNewCursor = new Bitmap(cursor.Width * 2 - hotX, cursor.Height * 2 - hotY);
            Graphics g = Graphics.FromImage(myNewCursor);
            g.Clear(Color.FromArgb(0, 0, 0, 0));
            g.DrawImage(cursor, cursor.Width - hotX, cursor.Height - hotY, cursor.Width,
            cursor.Height);
            this.Cursor = new Cursor(myNewCursor.GetHicon());

            g.Dispose();
            myNewCursor.Dispose();
        }

在你想要改变鼠标样式的事件里头使用这个方法就行了,如:
复制代码 代码如下:
private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap a=(Bitmap)Bitmap.FromFile("myCur.png");
            SetCursor(a, new Point(0, 0));
        }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/127224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号