高级会员
- 积分
- 758
- 金钱
- 758
- 注册时间
- 2012-8-23
- 在线时间
- 71 小时
|
发表于 2016-2-7 15:13:29
|
显示全部楼层
本帖最后由 月光疾風 于 2016-2-7 15:16 编辑
送上USB插拔检测代码一段
[mw_shl_code=csharp,true] // 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.
}[/mw_shl_code]
[mw_shl_code=csharp,true] /// <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拔出
{
MessageBox.Show("USB设备拔出!");
break;
}
case DBT_DEVICEARRIVAL: // USB插入获取对应串口名称
{
MessageBox.Show("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))));
Console.WriteLine("Port '" + portName + "' arrived.");
}*/
//自动搜索串口,并将其加入到[串口选择框]中
string[] SCIPorts;//字符串数组存放搜索到的COM口
SCIPorts = System.IO.Ports.SerialPort.GetPortNames();//获取所有COM口
this.UART_Num_ComboBox.Items.Clear();//首先将现有的项清除掉
int num = SCIPorts.Length;
//向[串口选择框]中添加搜索到的串口号
for (int i = 1; i <= SCIPorts.Length; i++)
{
this.UART_Num_ComboBox.Items.Add(SCIPorts[num - i]);
}
//UART_Num_ComboBox.Text
//设置各组合框的初始显示值
if (SCIPorts.Length != 0)
{
//初始值选择第一个Index的内容
this.UART_Num_ComboBox.SelectedIndex = 0;//串口号
this.UART_Speed_ComboBox.SelectedIndex = 0;//波特率
}
else
{
MessageBox.Show("没有可用的串口,请检查!");
}
break;
}
}
}
base.WndProc(ref m);
}[/mw_shl_code]
|
|