我将UserControl
从 Windows表单转换为 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中记录这些简单的鼠标事件吗?
答案 0 :(得分:2)
您可以以类似的方式处理消息(例如鼠标移动):
的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
}