1. 程式人生 > 其它 >C#更改應用的滑鼠指標

C#更改應用的滑鼠指標

第一種:(呼叫系統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")]

接下來使用自己的滑鼠樣式

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));
        }