1、用于监听Windows消息
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;//窗口过程
if (hwndSource != null)
hwndSource.AddHook(new HwndSourceHook(DeveiceChanged)); //挂钩
2、勾子函数
public const int WM_DEVICECHANGE = 0x219; //Windows消息编号 COM消息
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
//钩子函数
private IntPtr DeveiceChanged(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_DEVICECHANGE)
{
ComboBoxComReset();
switch (wParam.ToInt32())
{
case DBT_DEVICEARRIVAL://设备插入
break;
case DBT_DEVICEREMOVECOMPLETE: //设备卸载
if(PortIsOpen)
{
PortIsOpen = false;
ControlChange(true);
}
break;
default:
break;
}
}
return IntPtr.Zero;
}
本文介绍了一种使用C#实现的Windows设备变更监听方法。通过在应用程序中为指定窗口添加一个消息钩子,可以监听到设备的插入和移除事件。当检测到设备变化时,程序会根据不同的事件类型采取相应的措施。
1920

被折叠的 条评论
为什么被折叠?



