首先通过WindowInteropHelper类,我们可以获取WPF Window的Handle.
WindowInteropHelper helper = new WindowInteropHelper(window); IntPtr handle = helper.Handle;
然后,我们使用Handle可以创建一个HwndSource对象,HwndSource对象为我们提供了接口能够注册窗口消息的处理程序。
HwndSource hwndSource = HwndSource.FromHandle(handle); hwndSource.AddHook(new HwndSourceHook(HookProc)); private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // Handle the message. return IntPtr.Zero; }
说明:HwndSource是一个Win32窗体的托管实现,它所代表的Win32窗体能够呈现WPF的Content.同时该类型提供了接口对该Win32窗口进行处理。例如此处的注册窗口消息函数。