【发布时间】:2023-03-14 04:25:02
【问题描述】:
我在显示可用串行端口的不同 TabPages 上有一些组合框。我可以在组合框中选择一个端口并连接到它以获取数据。现在我希望组合框隐藏已经在使用的端口。最好的方法是什么?
这是组合框下拉菜单上发生的情况:
string[] portNames = SerialPort.GetPortNames();
comboBox9.Items.Clear();
foreach (var portName in portNames)
{
//checks if combox already contains same Item.
if (!comboBox9.Items.Contains(portNames))
{
comboBox9.Items.Add(portName);
}
}
private void button1_Click(object sender, EventArgs e)
{
//<-- This block ensures that no exceptions happen
if (_serialPort1 != null && _serialPort1.IsOpen)
_serialPort1.Close();
if (_serialPort1 != null)
_serialPort1.Dispose();
//<-- End of Block
if (comboBox2.Text != "")
{
_serialPort1 = new SerialPort(comboBox2.Text, BaudRate, Parity.Even, 7, StopBits.Two); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort1.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort1.Open(); //<-- make the comport listen
button1.Enabled = false;
button2.Enabled = true;
【问题讨论】:
-
您正在 for 循环之前创建组合框的所有项目。这会将所有端口添加到组合框。
SerialPort.GetPortNames()返回所有端口(空闲端口和正在使用的端口)? -
是的,它会返回免费的和正在使用的。
-
那么你如何决定哪一个是免费的,哪一个是正在使用的?
-
私有串行端口_serialPort1; _serialPort.IsOpen
-
好吧..这就是我的理解。您已经在组合框中填充了所有端口。现在,当您再次调用
SerialPort.GetPortName()时,您想检查哪些端口正在使用中,并且您想从组合框中删除这些端口。你能分享一下你首先在组合框中添加所有端口的代码吗?您编写了哪些代码来从组合框中删除正在使用的端口?
标签: c# combobox serial-port