GetCursorInfo WinForms vs WPF C#

Multi tool use
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());
}
The error is 87, I looked up on the System Code that is "The parameter is incorrect". That is very strange because PInvoke function's parameters are universial across all programming languages.
– Leo Long Vu
Jun 30 at 18:36
Maybe you call it too early in WPF? So basically the conditions when you can call that function are not correct in the WPF context. Not sure what those conditions are so this needs someone else to answer.
– rene
Jun 30 at 18:40
What I posted was actually the excact whole test code, the part left are just the using codes and class initialisation.
– Leo Long Vu
Jun 30 at 19:40
Can you move that code to the
Loaded
event?– rene
Jun 30 at 19:57
Loaded
1 Answer
1
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.
double
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.
It is indeed the problem with defining Point that is a very hard one to debug. Many thanks for the answer.
– Leo Long Vu
Jul 1 at 15:54
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That function supports GetLastError. Call that when it returns false to obtain the error code.
– rene
Jun 30 at 15:38