Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetCursorInfo WinForms vs WPF C#

I am having trouble of transferring pieces of my code from WinForms to WPF to have better control over the UI.

The following piece of code return True in WinForms but False in WPF. I suspect WPF panels have effects on the cursor so I tried start the app minimized but it still failed. Since the GetCursorInfo is PInvoke I think it should work the same within a programming language. Any advices on this?

    private CURSORINFO ci;

    [StructLayout(LayoutKind.Sequential)]
    public struct CURSORINFO
    {
        public Int32 cbSize;        // Specifies the size, in bytes, of the structure. 
        public Int32 flags;         // Specifies the cursor state.
        public IntPtr hCursor;      // Handle to the cursor. 
        Point point; // Should already marshal correctly.
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorInfo(ref CURSORINFO pci);

    public MainWindow()
    {
        InitializeComponent();

        ci = new CURSORINFO();

        ci.cbSize = Marshal.SizeOf(ci);

        MessageBox.Show(GetCursorInfo(ref ci).ToString());
    }    
like image 891
Leo Long Vu Avatar asked May 03 '26 14:05

Leo Long Vu


1 Answers

    Point point; // Should already marshal correctly.

It doesn't. Works for System.Drawing.Point but not for System.Windows.Point, the WPF type uses double for the X and Y members. So CURSORINFO.cbSize will be too large and that's enough to slap you with error 87 ("The parameter is incorrect"), it is too large.

Either type the name in full. Or if you don't want to add a reference to System.Drawing simply declare the POINT structure yourself. And don't forget that the returned info uses pixels as a unit, you typically want to convert to inches in a WPF app.

like image 195
Hans Passant Avatar answered May 05 '26 04:05

Hans Passant