C# 可用串口检测

C# 可用串口检测

直接上代码:

void comm_init()
{
    
    
    //Get all port list for selection
    //获得所有的端口列表,并显示在列表内
    PortList.Items.Clear();
    string[] Ports = SerialPort.GetPortNames();
    
    //获取所有可用串口
    for (int i = 0; i < Ports.Length; i++)
    {
    
    
        string s = Ports[i].ToUpper();
        Regex reg = new Regex("[^COM\\d]", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        s = reg.Replace(s, "");
        PortList.Items.Add(s);
    }
    
    if (Ports.Length > 1) //设定初始串口
    {
    
    
   	    PortList.SelectedIndex = 1;
    }
}

注意:
(1)需要添加命名空间using System.IO.Ports;
(2)UI界面上添加ComboBox 控件,并修改name为PortList。

猜你喜欢

转载自blog.csdn.net/CXYLVCHF/article/details/112030813