C#获取当前连接设备串口号
方案一: 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”) > -1)
{
string s = strs.Replace(“STMicroelectronics Virtual COM Port”, “”).Replace("(", “”).Replace(")", “”).Replace(" ", “”);
this.cobPorts.Items.Add(s);
if (cobPorts.Items.Count > 0)
{
this.cobPorts.SelectedIndex = 0;
}
}
}
方案三: 使用 SerialPort.GetPortNames()得到全部串口名称,并且逐个通信,通信OK则留下。也是我最终采取的方案
string[] ports = SerialPort.GetPortNames();
cobPorts.Items.Clear();
cobPorts.Text = null;
if (ports != null)
{
foreach (String sPort in ports)
{
if (sPort != null)
{
SerialPort spx = new SerialPort(sPort);
spx.Open();
bool com = false;
if (spx.IsOpen)
{
com = Communication(spx);
if (com == true)
{
cobPorts.Items.Add(sPort);
}
}
spx.Close();
}
}
}
if (cobPorts.Items.Count > 0)
{
// cobPorts.SelectedIndex = cobPorts.Items.IndexOf(Properties.Settings.Default.BluePort);
cobPorts.SelectedIndex = 0;
}
private bool Communication(SerialPort sPort)
{
try
{
sPort.BaudRate = 256000;
sPort.Parity = Parity.None;
sPort.DataBits = 8;
sPort.StopBits = StopBits.One;
sPort.Handshake = Handshake.RequestToSend;
sPort.ReceivedBytesThreshold = 1;
Byte[] sendBuffer = new Byte[] { 0xFA, 0xF5, 0x7, 0x4, 0x1, 0xD8, 0x3C };
// fm.slp.DiscardInBuffer();
// slp.DiscardOutBuffer();
int checkSum;
checkSum = fm.short_Data2CRC16(sendBuffer, sendBuffer.Count() - 2);
sendBuffer[5] = (Byte)(checkSum >> 8);
sendBuffer[6] = (Byte)(checkSum & 0xFF);
sPort.Write(sendBuffer, 0, sendBuffer.Count());
byte[] rbuf;
do
{
rbuf = new byte[sPort.BytesToRead];
// Console.WriteLine(rbuf.Length);
sPort.DiscardOutBuffer();
} while (rbuf.Length == 0); //此处循环 否则slp.BytesToRead有时获取到的值是0 调试的时刻有看到有值 ,获取出来为0,原因不明,循环一下就可以获取到了
sPort.Read(rbuf, 0, sPort.BytesToRead);
string str = "";
str = System.Text.Encoding.Default.GetString(rbuf);
if (str != "")
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
上一篇: 知识图谱3
下一篇: C# 删除注册表信息