WPF中處理消息首先要獲取窗口句柄,創建HwndSource對象 通過HwndSource對象添加消息處理回調函數.
HwndSource類: 實現其自己的窗口過程。 創建窗口之后使用 AddHook 和 RemoveHook 來添加和移除掛鈎,接收所有窗口消息。
private void UserControl_Loaded(object sender, RoutedEventArgs e) { HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;//窗口過程 if (hwndSource != null) hwndSource.AddHook(new HwndSourceHook(WndProc));//掛鈎 }
HwndSourceHook 類:委托,處理 Win32 窗口消息的方法。
實例:監測U盤的插入和拔出。
public const int WM_DEVICECHANGE = 0x219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WM_DEVICECHANGE) { switch (wParam.ToInt32()) { case DBT_DEVICEARRIVAL://U盤插入 m_selBox.Items.Clear(); InitCombox(); break; case DBT_DEVICEREMOVECOMPLETE: //U盤卸載 m_selBox.Items.Clear(); InitCombox(); break; default: break; } } return IntPtr.Zero; }
