首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#窗口应用程序中使用自定义彩色光标

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

Stack Overflow用户
提问于 2010-11-30 00:33:21
回答 5查看 13.2K关注 0票数 6

我正在开发一个SDG (Single Display Groupware)应用程序,为此,我需要为单个窗口使用多个光标(最简单的不同颜色)。我知道在C#中你只能使用黑白光标,但这并不能解决我的问题。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-11-30 02:51:49

游标类做得相当糟糕。由于某种神秘的原因,它使用了传统的COM接口(IPicture),该接口不支持彩色和动画光标。它可以用一些相当丑陋的肘部油脂来修复:

代码语言:javascript
复制
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);
}

示例用法:

代码语言:javascript
复制
this.Cursor = NativeMethods.LoadCustomCursor(@"c:\windows\cursors\aero_busy.ani");
票数 13
EN

Stack Overflow用户

发布于 2010-11-30 18:42:34

我也尝试了一些不同的方法,它似乎可以处理不同颜色的光标,但这段代码的唯一问题是鼠标光标的热点坐标不准确,即鼠标光标稍微向右移动。但这可以通过考虑代码中的偏移量来修复。

代码如下:

代码语言:javascript
复制
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;

        }
    }
}
票数 3
EN

Stack Overflow用户

发布于 2020-05-08 13:58:43

这个帖子很老了,但它是Google上最早的热门话题之一,所以这里是VS 2019的答案:

代码语言:javascript
复制
someControl.Cursor = new Cursor(Properties.Resources.somePNG.GetHicon());

您应该添加“somePNG.png”作为项目资源,它具有任何您喜欢的透明度。

希望它能帮助2020年的某个人。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4305800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档