C#中USB转串口的拔插捕获
// usb消息定义
public const int wm_device_change = 0x219;
public const int dbt_devicearrival = 0x8000;
public const int dbt_device_remove_complete = 0x8004;
public const uint32 dbt_devtyp_port = 0x00000003;
[structlayout(layoutkind.sequential)]
struct dev_broadcast_hdr
{
public uint32 dbch_size;
public uint32 dbch_devicetype;
public uint32 dbch_reserved;
}
[structlayout(layoutkind.sequential)]
protected struct dev_broadcast_port_fixed
{
public uint dbcp_size;
public uint dbcp_devicetype;
public uint dbcp_reserved;
// variable?length field dbcp_name is declared here in the c header file.
}
/// <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拔出
dev_broadcast_hdr dbhd = (dev_broadcast_hdr)marshal.ptrtostructure(m.lparam, typeof(dev_broadcast_hdr));
if (dbhd.dbch_devicetype == dbt_devtyp_port)
{
string portname = marshal.ptrtostringuni((intptr)(m.lparam.toint32() + marshal.sizeof(typeof(dev_broadcast_port_fixed))));
if (cbport.items.contains(portname))
{
cbport.items.remove(portname);
}
if (wr != null)
{
wr.close();
}
}
break;
case dbt_devicearrival: // usb插入获取对应串口名称
dev_broadcast_hdr dbhdr = (dev_broadcast_hdr)marshal.ptrtostructure(m.lparam, typeof(dev_broadcast_hdr));
if (dbhdr.dbch_devicetype == dbt_devtyp_port)
{
string portname = marshal.ptrtostringuni((intptr)(m.lparam.toint32() + marshal.sizeof(typeof(dev_broadcast_port_fixed))));
if (!cbport.items.contains(portname))
{
cbport.items.add(portname);
}
}
break;
}
}
base.wndproc(ref m);
}
上一篇: C# 创建含多层分类标签的Excel图表
下一篇: 360通用php防护代码(使用操作详解)