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

问题描述:

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

在此先感谢。

+0

颜色光标做工精细。你是怎么发现你只能使用黑白游标的? – 2010-11-29 16:37:44

+0

而且Windows会让你有多于一个的光标? – 2010-11-29 16:38:12

光标类是做相当差。由于一些神秘的原因,它使用传统的COM接口(IPicture),该接口不支持彩色和动画光标。它是可以解决一些非常丑陋的苦劳:

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

您可以从文件加载光标动态如下:

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

你已经装好了之后,你可以这样设置任何控制的光标:

myControl.Cursor = myCursor; 

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

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

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

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

但是,有一些应用程序在一台PC上支持多个输入。 (例如,Rag Doll Kung Fu)为此,您正在查看.NET框架不支持的内容。

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

我曾经需要动态地创建动态游标。原来,这构成了奇怪的问题,尤其是因为半透明会混合黑色并使光标变得太暗。最后,我解决了这个问题,从多所社区一些帮助,在这里显示的整体解决方案:

Windows Forms: Making a cursor bitmap partially transparent

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

的代码如下:

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; 

     } 
    } 
}