none
C# Winform 控件鼠标指针问题 RRS feed

  • 问题

  • 操作系统为Windows10,现在把Winform里面的按钮控件的Cursor属性设置为Hand手型,但是鼠标移上去时显示的手型是Windows XP的样子,怎么让它成为和当前系统手型鼠标指针一致呢?

    2017年1月19日 9:29

答案

  • 你好,

    可以使用自定义Cursor 来实现它。下面是一个自定义Cursor的静态类。

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

    #用法

    button1.Cursor = NativeMethods.LoadCustomCursor(@"C:\Windows\Cursors\aero_link.cur");

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已标记为答案 DomadoM 2017年1月22日 5:12
    2017年1月20日 5:58
    版主