欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-11 09:10:40
// usb消息定义 public const int WM_DEVICE_CHANGE = 0x219; public const int DBT_DEVICEARRIVAL = 0x8000; public const int DBT_DEVICE_REMOVE_COMPLETE = 0x800 ......

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