zoukankan      html  css  js  c++  java
  • 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));
            }

  • 相关阅读:
    Hello iOS
    钝化程序、逻辑冻结、冻结程序的延续、瞬间转移
    对字符串操作的各种笔试题
    .NET各大平台数据列表控件绑定原理及比较(WebForm、Winform、WPF)
    多线程计算----pthread
    Xcode的Hello World(简单易懂)
    two sets of Qt binaries into the same process的解决办法
    微软新一代输入法框架 TSF
    Starting the application on Mac does not work(拷贝platforms到不同的位置,才能解决问题),还可设置DYLD_PRINT_LIBRARIES=1 观察动态库
    dddd
  • 原文地址:https://www.cnblogs.com/Johar/p/8288093.html
Copyright © 2011-2022 走看看