WPF 如何将一个窗口的所有事件重定向到另一个窗口
解决方案
你之前的方案只能转发原生Win32消息,WPF路由事件未被触发的核心原因是:WPF内部会通过ComponentDispatcher对收到的Win32消息做二次封装,生成对应的WPF输入事件(比如MouseEnter、Click等)再分发到对应控件,直接转发原始Win32消息跳过了WPF的事件封装流程。
具体实现步骤
- 订阅
ComponentDispatcher.ThreadPreprocessMessage事件,捕获当前线程所有待处理的输入消息 - 筛选属于Window1的消息,对鼠标类消息做坐标转换,将Window1的客户区坐标转换为Window2的客户区坐标
- 将处理后的消息发送给Window2,触发Window2的WPF事件封装流程
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; public partial class MainWindow : Window { private Window _window2; private IntPtr _window1Hwnd; private IntPtr _window2Hwnd; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint); [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint); [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X; public int Y; } public MainWindow() { InitializeComponent(); _window2 = new Window2(); _window2.Show(); } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); // 获取两个窗口的句柄 _window1Hwnd = new WindowInteropHelper(this).EnsureHandle(); _window2Hwnd = new WindowInteropHelper(_window2).EnsureHandle(); // 监听线程消息预处理事件 ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage; } private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { // 只处理属于Window1的输入类消息,过滤窗口管理类消息避免冲突 if (msg.hwnd == _window1Hwnd && IsInputMessage(msg.message)) { // 转换鼠标坐标 if (IsMouseMessage(msg.message)) { POINT point = new POINT { X = (int)(msg.lParam.ToInt32() & 0xFFFF), Y = (int)(msg.lParam.ToInt32() >> 16) }; // 先转为屏幕坐标 ClientToScreen(_window1Hwnd, ref point); // 再转为Window2的客户区坐标 ScreenToClient(_window2Hwnd, ref point); // 重组lParam参数 msg.lParam = (IntPtr)((point.Y << 16) | (point.X & 0xFFFF)); } // 转发消息到Window2 SendMessage(_window2Hwnd, msg.message, msg.wParam, msg.lParam); // 可选:如果不需要Window1响应事件,设置handled = true拦截消息 // handled = true; } } // 判断是否为输入类消息(覆盖键盘、鼠标、触控等输入范围) private bool IsInputMessage(int msg) { return msg >= 0x000F && msg <= 0x02FF; } // 判断是否为鼠标消息 private bool IsMouseMessage(int msg) { return msg >= 0x0200 && msg <= 0x020E; } protected override void OnClosed(EventArgs e) { base.OnClosed(e); // 取消订阅避免内存泄漏 ComponentDispatcher.ThreadPreprocessMessage -= ComponentDispatcher_ThreadPreprocessMessage; } }
注意事项
- 若要保证控件对应准确,需要Window1和Window2的对应控件布局、尺寸完全一致
- 可根据实际需求调整
IsInputMessage的过滤范围,避免转发不需要的系统消息造成窗口异常 - 若两个窗口不在同一个UI线程,需要通过
Dispatcher跨线程转发消息
内容的提问来源于stack exchange,提问作者Selastin
相关产品推荐
相关产品推荐

