C#获取串口完整名字、并实时监听串口插拔
1,首先利用System.Management里面提供的类(第一次可能需要添加对System.Management的引用,否则找不到类),获取串口完整名字
2,监听窗口USB插拔事件并更新下拉列表中的串口
///
/// 获取串口完整名字(包括驱动名字)
/// 如果找不到类,需要添加System.Management引用,添加引用->程序集->System.Management
///
Dictionary coms = new Dictionary();
private void getPortDeviceName()
{coms.Clear();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher
("select * from Win32_PnPEntity where Name like '%(COM%'"))
{
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties["Name"].Value != null)
{
string deviceName = hardInfo.Properties["Name"].Value.ToString();
int startIndex = deviceName.IndexOf("(");
int endIndex = deviceName.IndexOf(")");
string key = deviceName.Substring(startIndex + 1, deviceName.Length - startIndex - 2);
string name = deviceName.Substring(0, startIndex - 1);
Console.WriteLine("key:"+key+",name:"+name+",deviceName:"+deviceName);
coms.Add(key,name);
}
}//创建一个用来更新UI的委托 (主线程更新)
this.Invoke(
new Action(() =>
{
comboBox1.Items.Clear();
foreach (KeyValuePair kvp in coms)
{
comboBox1.Items.Add(kvp.Key + " " + kvp.Value);
//更新下拉列表中的串口
}})
);
}}public const int WM_DEVICE_CHANGE = 0x219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICE_REMOVE_COMPLETE = 0x8004;
///
/// 检测USB串口的拔插
///
///
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拔出
{new Thread(
new ThreadStart(
new Action(() =>
{
getPortDeviceName();
})
)
).Start();
}
break;
case DBT_DEVICEARRIVAL: // USB插入获取对应串口名称
{
new Thread(
new ThreadStart(
new Action(() =>
{
getPortDeviceName();
})
)
).Start();
}
break;
}
}
base.WndProc(ref m);
}
【C#获取串口完整名字、并实时监听串口插拔】
推荐阅读
- EditText默认不获取焦点弹出键盘
- whlie循环和for循环的应用
- 【实用教程】4种获取无水印视频素材的方法
- 插件化无法获取或找到.so文件
- SpringBoot整合MongoDB完整实例代码
- 获取知识的门槛
- 提取ipa|提取ipa 包内资源
- 音乐之声(二)
- SpringBoot|SpringBoot 属性配置中获取值的方式
- django|django 获取用户的域名