我正在开发一个SDG (Single Display Groupware)应用程序,为此,我需要为单个窗口使用多个光标(最简单的不同颜色)。我知道在C#中你只能使用黑白光标,但这并不能解决我的问题。
发布于 2010-11-30 02:51:49
游标类做得相当糟糕。由于某种神秘的原因,它使用了传统的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");发布于 2010-11-30 18:42:34
我也尝试了一些不同的方法,它似乎可以处理不同颜色的光标,但这段代码的唯一问题是鼠标光标的热点坐标不准确,即鼠标光标稍微向右移动。但这可以通过考虑代码中的偏移量来修复。
代码如下:
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;
}
}
}发布于 2020-05-08 13:58:43
这个帖子很老了,但它是Google上最早的热门话题之一,所以这里是VS 2019的答案:
someControl.Cursor = new Cursor(Properties.Resources.somePNG.GetHicon());您应该添加“somePNG.png”作为项目资源,它具有任何您喜欢的透明度。
希望它能帮助2020年的某个人。
https://stackoverflow.com/questions/4305800
复制相似问题