WPF处理Windows消息

时间:2022-01-02 04:16:29

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;
}