:C# 搜索系统串口方法(0001)
语 言:C#
项目框架:NET Framework 4.7
编译工具:Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.8.3
实现方法
1、新建一个 combobox 控件,用于显示串口和收集串口集合;
2、新建一个 ricetextbox 控件,用于显示操作记录;
3、主要应用方法:SerialPort.GetPortNames();
代码如下:
// 搜索电脑的串口,并加载到 combobox 下拉菜单,
public void searchCom()
{
this.cobComList.Items.Clear(); //清除下拉菜单集合
string[] ComParts = SerialPort.GetPortNames(); //新建字符串数组存,获取系统当前串口
if (ComParts.Length == 0) //判断串口数据是不是为0,如果是 Logo 提示
{
this.rtbLogoText.Clear(); //清除LOGO显示
this.rtbLogoText.AppendText("没有串口,请插入串口设备!\r\n");
this.cobComList.Items.Clear(); //清除串口下拉菜单集合
this.cobComList.Text = null; // 清除串口显示口文字
}
else
{
this.rtbLogoText.Clear();
//将串口字符逐个加到串口下拉菜单集合
for (int i = 0; i < ComParts.Length; i++)
{
this.rtbLogoText.AppendText(ComParts[i] + "\r\n");//显示搜索到的串口
this.cobComList.Items.Add(ComParts[i]);//加到串口集合下拉菜单
}
this.cobComList.Text = ComParts[0]; //选择第一个串口
}
this.rtbLogoText.ScrollToCaret(); //跳到最新行
}