可参考:http://www.jb51.net/article/54386.htm
采用windows的消息机制来捕获插入的usb状态,然后,获取对应的串口名称。代码如下:
// usb消息定义
public const int WM_DEVICE_CHANGE = 0x219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICE_REMOVE_COMPLETE = 0x8004;
/// <summary>
/// 检测USB串口的拔插
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DEVICE_CHANGE) // 捕获USB设备的拔出消息WM_DEVICECHANGE
{
switch (m.WParam.ToInt32())
{
case DBT_DEVICE_REMOVE_COMPLETE: // USB拔出
{
}
break;
case DBT_DEVICEARRIVAL: // USB插入获取对应串口名称
{
}
break;
}
}
base.WndProc(ref m);
}