【发布时间】:2018-06-30 14:56:15
【问题描述】:
我无法将我的代码片段从 WinForms 传输到 WPF,以便更好地控制 UI。
以下代码在 WinForms 中返回 True,但在 WPF 中返回 False。我怀疑 WPF 面板对光标有影响,所以我尝试最小化启动应用程序,但它仍然失败。由于 GetCursorInfo 是 PInvoke,我认为它应该在编程语言中同样工作。对此有何建议?
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());
}
【问题讨论】:
-
该功能支持GetLastError。返回false时调用,获取错误码。
-
错误是87,我查了系统代码是“参数不正确”。这很奇怪,因为 PInvoke 函数的参数在所有编程语言中都是通用的。
-
也许你在 WPF 中称它为时过早?所以基本上你可以调用该函数的条件在 WPF 上下文中是不正确的。不知道这些条件是什么,所以这需要其他人来回答。
-
我贴的其实是完整的测试代码,剩下的只是使用代码和类初始化。
-
您可以将该代码移至
Loaded事件吗?