代码之家  ›  专栏  ›  技术社区  ›  Matan Yashar

C#获取当前光标图标

  •  4
  • Matan Yashar  · 技术社区  · 7 年前

    [DllImport("user32.dll")]
    static extern bool SetSystemCursor(IntPtr hcur, uint id);
    
    [DllImport("user32.dll", EntryPoint = "GetCursorInfo")]
    public static extern bool GetCursorInfo(out CURSORINFO pci);
    
    [DllImport("user32.dll", EntryPoint = "CopyIcon")]
    public static extern IntPtr CopyIcon(IntPtr hIcon);
    
    [StructLayout(LayoutKind.Sequential)]
    public struct CURSORINFO
    {
        public Int32 cbSize;        // Specifies the size, in bytes, of the structure. 
        public Int32 flags;         // Specifies the cursor state. This parameter can be one of the following values:
        public IntPtr hCursor;          // Handle to the cursor. 
        public POINT ptScreenPos;       // A POINT structure that receives the screen coordinates of the cursor. 
    }
    
    public void etc()
    {
        IntPtr hwndic = new IntPtr();
        CURSORINFO curin = new CURSORINFO();
        curin.cbSize = Marshal.SizeOf(curin);
        if (GetCursorInfo(out curin))
        {
            if (curin.flags == CURSOR_SHOWING)
            {
                hwndic = CopyIcon(curin.hCursor);
                SetSystemCursor(hwndic, OCR_NORMAL);
            }
        }
    }
    

    问题是复制的图标有时不同于默认的鼠标图标,例如,如果它在等待位置捕捉到它,那么它可能会给我鼠标等待图标。

    提前谢谢。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Matan Yashar    7 年前

    我已经解决了我的问题,经过一些研究,我得到了一些有趣的东西,可能会一直有效。

    我注意到,每当我更改光标图标(例如使用代码,更改为一些随机图标)时,每当我转到windows光标设置时,图标不会在那里更改,但没有应用按钮来应用我以前的设置,因为windows认为我正在使用这些设置。

    因此,我在没有应用的情况下将设置更改为一些随机的其他设置,并返回到我之前应用的设置,这样做会将光标重置为任何更改之前的原始光标。

    因此,windows只是在“刷新”鼠标,所以我就这么做了,也许如果我能强制刷新,一切都会很完美,所以我找到了一种方法,使用这个功能:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32 SystemParametersInfo(UInt32 uiAction,UInt32 uiParam, String pvParam, UInt32 fWinIni);
    

    在观看msdn时,我在其参数中发现了一些有趣的东西,参数“SPI\u SETCURSORS(0x57)”,我引用:

    所以我试过了,它成功了,这个过程的例子:

    [DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
    private static extern IntPtr LoadCursorFromFile(String str);
    
    uint SPI_SETCURSORS = 0x57;
    var NewArrow = LoadCursorFromFile("C:\\Users\\mtnju\\Downloads\\invisible.cur"); // loads some new cursor icon using the LoadCursorFromFile function
    SetSystemCursor(NewArrow, OCR_NORMAL); // sets the new cursor icon using the SetSystemCursor function
    SystemParametersInfo(SPI_SETCURSORS, 0, null, 0);// reloads all of the system cursors
    

    我想我需要5分钟来做这样的事情……我希望它能帮助你们,我真的很感谢你们的评论试图帮助我。