今天遇到一个需求,需要用大量自定义图片根据不同情况来改变cursor的形状。由于在wpf页面中,调用c++的window.无法控制,只能改变系统鼠标的状态,在网络上查了相关资料发现并没有完整的实现例子,很多的例子肯定运行不了。故在这里整理下 发给大家。
1 需要调用的api 包括:
[DllImport("user32.dll")]
static extern bool SetSystemCursor(IntPtr hcur, uint id);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetCursor();
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CopyIcon(IntPtr hInstance);
[DllImport("User32.DLL")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam,
IntPtr pvParam, uint fWinIni);
第一步添加图片:将该图片的build Action 改成Embedded Resource ;
在程序启动的时候 将图片载入到内存当中:
public static IntPtr SIECURSORLeftBottom2RightTopArrowMouseCursor
{
get
{
if (sIECURSORLeftBottom2RightTopArrowMouseCursor == (IntPtr)0)
{
Bitmap image = new Bitmap(asm.GetManifestResourceStream(SIECURSORLeftBottom2RightTopArrowImageResourseName));
sIECURSORLeftBottom2RightTopArrowMouseCursor = image.GetHicon();
}
return sIECURSORLeftBottom2RightTopArrowMouseCursor;
}
}
private static readonly Assembly asm = Assembly.GetExecutingAssembly();
private const string SIECURSORLeftBottom2RightTopArrowImageResourseName = "图片路径";
写一个static方法
public static void SetCursor(SIECURSOR siecursor) // cursor 的enum
{
IntPtr intPtr = default(IntPtr);
switch (siecursor)
{
case SIECURSOR.SIECURSORNormal:
intPtr = SIECURSORNormalMouseCursor;
break;
case SIECURSOR.SIECURSORLeftBottom2RightTopArrow:
intPtr = SIECURSORLeftBottom2RightTopArrowMouseCursor;
break;
}
// Save old Cursor Intptr
hOldCur = CopyIcon(intPtr);
SetSystemCursor(hOldCur, OCR_NORMAL);
}
在这里需要注意一下,必须保存hOldCur
const int OCR_NORMAL = 32512; //必须
private static IntPtr hOldCur;
到这里 只需要通过不同的方法调传不同的enum 就可以。
当程序退出的时候 需要
if (IssetCursorNormal)
/// setSystemNormalCursor
SystemParametersInfo(SPI_SETCURSORS, 0, IntPtr.Zero, SPIF_SENDWININICHANGE);
去把系统cursor 恢复成最原始的状态,代码经过测试无任何文图,希望对大家有帮助。