c# - WPF 拦截全局鼠标移动(就像在 Windows 窗体中使用 IMessageFilter)

标签 c# wpf mouseevent imessagefilter

我正在将 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;
    }

当然,如果您不想以 native 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
}

关于c# - WPF 拦截全局鼠标移动(就像在 Windows 窗体中使用 IMessageFilter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37485091/

相关文章:

c# - 为什么另一个应用程序窗口标题中的文本不正确?

wpf - 如何在 XAML 中设置 ItemsSource?

c# - VS 2017 : The security debugging option is set but it requires the Visual Studio hosting process which is unavailable

css - onmouseover 事件不适用于移动设备

iphone - 在 Mac 上模拟鼠标

c# - 如何在 Windows 窗体中动态加载面板?

c# - C# 是否支持函数组合?

c# - 使用 Graph API c# unity3d 访问 facebook 的帖子等

.net - 在控件上设置边距、宽度绑定(bind)到实际宽度会导致 VS2012 崩溃

Angular - 如何解析 event.path 内的对象