我想获得相对于屏幕坐标的鼠标位置。我使用以下代码来做到这一点。
window.PointToScreen(Mouse.GetPosition(window));
它按预期工作。但我的MouseMove事件没有在MainWindow外面发射。也就是说,如果我将鼠标移到桌面上并恢复了我的窗口。
任何想法都赞赏。
答案 0 :(得分:10)
使用CaptureMouse()方法。
对于上面的示例,您可以添加:
window.CaptureMouse();
在MouseDown事件处理程序中的代码隐藏中。
然后您需要致电:
window.ReleaseMouseCapture();
在MouseUp事件处理程序中的代码隐藏中。
答案 1 :(得分:1)
无论是否按下任何鼠标按钮,我都需要能够捕获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();
}
}
效果很好!