在C#Windows应用程序中使用自定义彩色光标

我正在开发一个SDG(单显示组件)应用程序,为此我需要多个光标(对于最简单的不同颜色)用于单个窗口。 我开始知道,用C#你可以使用黑白游标,这不能解决我的问题。 所以请帮助我解决这个问题。

提前致谢。

Cursor类很难完成。 由于一些神秘的原因,它使用传统的COM接口(IPicture),该接口不支持彩色和animation游标。 它可以用一些相当难看的手肘润滑脂来固定:

using System; using System.ComponentModel; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Reflection; static class NativeMethods { public static Cursor LoadCustomCursor(string path) { IntPtr hCurs = LoadCursorFromFile(path); if (hCurs == IntPtr.Zero) throw new Win32Exception(); var curs = new Cursor(hCurs); // Note: force the cursor to own the handle so it gets released properly var fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance); fi.SetValue(curs, true); return curs; } [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern IntPtr LoadCursorFromFile(string path); } 

示例用法:

 this.Cursor = NativeMethods.LoadCustomCursor(@"c:\windows\cursors\aero_busy.ani"); 

我也尝试了一些不同的东西,它似乎与不同的彩色游标工作,但这段代码唯一的问题是,鼠标光标的热点坐标不准确,即稍微向右移动。 但是这可以通过考虑代码中的偏移量来解决。

代码如下:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; namespace MID { public partial class CustomCursor : Form { [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr LoadCursorFromFile(string filename); public CustomCursor() { InitializeComponent(); Bitmap bmp = (Bitmap)Bitmap.FromFile("Path of the cursor file saved as .bmp"); bmp.MakeTransparent(Color.Black); IntPtr ptr1 = blue.GetHicon(); Cursor cur = new Cursor(ptr1); this.Cursor = cur; } } } 

您可以像这样dynamic加载文件中的游标:

 var myCursor = new Cursor("myCursor.cur"); 

加载之后,可以像这样设置任何控件的光标:

 myControl.Cursor = myCursor; 

游标也接受stream作为构造函数参数。 这意味着您可以从应用程序中embedded的资源加载,而不是从文件系统加载。

Windows不会让你有多个游标,但是你可以在你的控件上绘制多个游标。 你可以像这样使用游标对象的Draw方法:

 myCursor.Draw(g, new Rectangle(...)); 

如果您使用TCP / IP在客户端之间发送游标数据,那么这应该足以工作。

但是,有一些应用程序在一台PC上支持多个input。 (例如, 布娃娃功夫 )为此,你正在寻找的东西,NET框架不支持。

您可能不得不查看一些USB调用PInvoking。 (我在这里没有太多的经验,所以我不能精心策划)

我曾经需要dynamic创builddynamic游标。 事实certificate这个问题很奇怪,特别是因为半透明会混合黑色,使得光标太黑。 最后,我从SO社区的一些帮助下解决了这个问题,整个解决scheme显示在这里:

Windows窗体:使光标位图部分透明