我想获取相对于屏幕坐标系的鼠标位置。我正在使用以下代码来实现。
window.PointToScreen(Mouse.GetPosition(window));
它按预期工作。但是我的MouseMove事件在MainWindow之外没有触发。也就是说,如果我将窗口还原并在桌面上移动鼠标,事件不会被触发。
欢迎任何想法。
使用CaptureMouse()方法。
对于您上面的例子,您可以添加:
window.CaptureMouse();
在你的代码后台(code-behind)中的MouseDown事件处理程序内。
然后你需要调用:
window.ReleaseMouseCapture();
在你的代码后台里面,在MouseUp事件处理程序中。
我需要能够在WPF窗口外捕获鼠标位置,而不受任何鼠标按钮按下的限制。最终,我使用Interop调用了WINAPI GetCursorPos,并结合线程而不是窗口事件来实现。
using System.Runtime.InteropServices;
using Point = System.Drawing.Point;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(ref Point lpPoint);
public MainWindow()
{
InitializeComponent();
new Thread(() =>
{
while (true)
{
//Logic
Point p = new Point();
GetCursorPos(ref p);
//Update UI
Dispatcher.BeginInvoke(new Action(() =>
{
Position.Text = p.X + ", " + p.Y;
}));
Thread.Sleep(100);
}
}).Start();
}
}
非常好用!