Mouse Move not trigger outside WPF Main Window

最后都变了- 提交于 2019-12-23 08:03:16

问题


I want to get mouse position relative to screen coordinates. I am using the following code to do that.

window.PointToScreen(Mouse.GetPosition(window));

It is working as expected. But my MouseMove event not firing outside the MainWindow. That is if I move my mouse over desktop with my window restored.

Any ideas appreciated.


回答1:


Use the CaptureMouse() method.

For your example above, you could add:

window.CaptureMouse();

in your code-behind inside the MouseDown event handler.

You then need to call:

window.ReleaseMouseCapture();

in your code-behind inside the MouseUp event handler.




回答2:


I needed to be able to capture mouse position outside of the WPF window regardless of any mouse button pressed. I ended up using Interop to call a WINAPI GetCursorPos combined with a thread instead of an event for the window.

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();
    }
}

Works great!



来源:https://stackoverflow.com/questions/10330452/mouse-move-not-trigger-outside-wpf-main-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!