方案一: string[] ports = SerialPort.GetPortNames();
会把鼠标键盘等其他不想获取到的串口也一并获取到
方案二:调用API,获取设备管理器下串口序列名称,可以自定义筛选。但是存在BUG,列如某个产品在设备管理器中连接后为STMicroelectronics Virtual COM Port,正常是STMicroelectronics Virtual COM Port(COMX).出现这种情况这种方法就不行了
ManagementObjectSearcher searcher = new ManagementObjectSearcher(“select * from Win32_SerialPort Where Name like ‘%STMicroelectronics Virtual COM Port%’”);
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties[“Name”] != null)
{
if (strs.IndexOf(“STMicroelectronics Virtual COM Port”) > -1)
{
break;
}
strs = strs + hardInfo.Properties[“Name”].Value.ToString();
}
}
this.cobPorts.Items.Clear();
if (!string.IsNullOrEmpty(strs))
{
if (strs.IndexOf(“STMicroelectronics Virtual COM Port”
C#获取当前连接设备串口号
最新推荐文章于 2024-04-28 09:04:37 发布