有的时候,一个自定义的鼠标光标能给你的程序增色不少。本文这里介绍一下如何在.net桌面程序中自定义鼠标光标。由于.net的桌面程序分为WinForm和WPF两种,这里分别介绍一下。
WinForm程序
对于WinForm程序,可以通过修改Control.Cursor属性来实现光标的修改,如果我们有光标文件的话,可以直接通过如下代码实现自定义光标:
this.Cursor = new Cursor("myCursor.cur");
但这种方式不是本文介绍的重点,本文主要介绍如何自己绘制光标,这样则具有更多的可控性和灵活性。
创建一个自定义光标,首先需要定义需要一个光标结构 ICONINFO ,它的.net版本如下:
public struct IconInfo
{
public
bool
fIcon;
public
int
xHotspot;
public
int
yHotspot;
public
IntPtr
hbmMask;
public
IntPtr
hbmColor;
}
然后通过GetIconInfo and CreateIconIndirect两个函数来合成光标。完整代码如下:
1 public class CursorHelper 2 { 3 static class NativeMethods 4 { 5 public struct IconInfo 6 { 7 public bool fIcon; 8 public int xHotspot; 9 public int yHotspot; 10 public IntPtr hbmMask; 11 public IntPtr hbmColor; 12 } 13 14 [DllImport("user32.dll")] 15 public static extern IntPtr CreateIconIndirect(ref IconInfo icon); 16 17 18 [DllImport("user32.dll")] 19 [return: MarshalAs(UnmanagedType.Bool)] 20 public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo); 21 } 22 23 public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot) 24 { 25 var icon = new NativeMethods.IconInfo 26 { 27 xHotspot = xHotSpot, 28 yHotspot = yHotSpot, 29 fIcon = false 30 }; 31 32 NativeMethods.GetIconInfo(bmp.GetHicon(), ref icon); 33 return new Cursor(NativeMethods.CreateIconIndirect(ref icon)); 34 } 35 }