首先通過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窗口進行處理。例如此處的注冊窗口消息函數。