WPF拦截全局鼠标移动(如在Windows表单中使用IMessageFilter)

WPF Intercept global mouse movements (like using IMessageFilter in Windows Form)

我正在将 UserControlWindows 格式 转换为 WPF,这是我的 Windows 表格 工作代码:

GlobalMouseHandler mouseHandler = new GlobalMouseHandler();
mouseHandler.MouseMove += OnGlobalMouseMove;
mouseHandler.MouseButtonUp += OnGlobalMouseButtonUp;

public class GlobalMouseHandler : IMessageFilter, IDisposable
{
    public event MouseMovedEvent MouseMove;
    public event MouseButtonUpEvent MouseButtonUp;

    public GlobalMouseHandler(){
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_MOUSEMOVE:
                MouseMove?.Invoke();
                break;
            case WM_LBUTTONUP:
                MouseButtonUp?.Invoke();
                break;
        }
        return false;
    }
}

我使用 IMessageFilter 在我的应用程序中获取鼠标移动和鼠标松开事件并附加到它们。

现在,我知道了 IMessageFilter is not available in WPF,但是有没有一种简单的方法可以在 WPF 中记录这些简单的鼠标事件?

您可以用类似的方式处理消息(例如鼠标移动):

Xaml:

<Window ... Loaded="Window_OnLoaded">
    ...
</Window>

代码隐藏:

    using System.Windows.Interop;

    ...

    private const int WM_MOUSEMOVE = 0x0200;

    private void Window_OnLoaded(object sender, RoutedEventArgs e)
    {
        HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook(this.WndProc);
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case WM_MOUSEMOVE:
                // MouseMove?.Invoke();
                break;
        }

        return IntPtr.Zero;
    }

当然,如果您不想以本机 WPF 方式执行此操作(例如左键向上):

<Window ... PreviewMouseLeftButtonUp="Window_OnPreviewMouseLeftButtonUp">
    ...
</Window>

private void Window_OnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // e.Handled = true if you want to prevent following MouseLeftButtonUp event processing
}