当前位置: 移动技术网 > IT编程>开发语言>.net > C#中USB转串口的拔插捕获

C#中USB转串口的拔插捕获

2019年04月09日  | 移动技术网IT编程  | 我要评论

店宝宝和客户达哪个好,中九联盟,麻城热线

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网