在 C# 中从组合框中添加/删除 COM 端口
我正在尝试编写一个程序,利用 ComboBox 来显示从以下方法获得的当前连接的 COM 端口:
System.IO.Ports.SerialPort.GetPortNames()
这个想法是初始化一个线程,每秒检查当前可用的 COM 端口,并相应地更新 ComboBox。尽管我尽了最大努力,我还是无法让它发挥作用。
更新组合框内容的代码如下:
private void Form1_Load(object sender, EventArgs e)
{
availPorts = new BindingList<String>();
Thread t = new Thread(new ThreadStart(update));
t.Start();
}
private void update()
{
this.comboBox1.DataSource = availPorts;
while (true)
{
Console.WriteLine("CHECK");
foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
{
if (!availPorts.Contains(port))
{
Console.WriteLine("FOUND");
availPorts.Add(port);
}
}
Thread.Sleep(1000);
}
}
找到端口时我可以看到控制台消息,但组合框仍然为空。任何帮助将不胜感激。
I am attempting to write a program that utilizes a ComboBox to display currently connected COM ports obtained from the following method:
System.IO.Ports.SerialPort.GetPortNames()
The idea is to initialize a thread that checks the currently available COM ports every second, and update the ComboBox accordingly. Despite my best efforts, I can't get it to work.
The code to update the ComboBox's contents is the following:
private void Form1_Load(object sender, EventArgs e)
{
availPorts = new BindingList<String>();
Thread t = new Thread(new ThreadStart(update));
t.Start();
}
private void update()
{
this.comboBox1.DataSource = availPorts;
while (true)
{
Console.WriteLine("CHECK");
foreach (String port in System.IO.Ports.SerialPort.GetPortNames())
{
if (!availPorts.Contains(port))
{
Console.WriteLine("FOUND");
availPorts.Add(port);
}
}
Thread.Sleep(1000);
}
}
I can see the console messages as the ports are found, however the ComboBox remains empty. Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试像这样修改代码。
Try modify code like this.
ComboBox 未更新,因为创建运行更新方法的线程正在尝试更新属于另一个线程的可视控件。在大多数情况下,这会引发错误,但这里不会。
我通过首先创建一个独立于更新的方法解决了这个问题,该方法仅处理向数据源添加 COM 端口名称。在此方法中,有一个 if 语句检查是否需要调用:
如果需要调用,则通过委托在正确的线程中调用该方法:
这会导致 ComboBox 在通过连续执行检测到新的 COM 端口时进行更新更新方法。可以编写类似的方法来删除已与系统断开连接的 COM 端口。只是不要忘记在窗体关闭时结束线程,否则它将无限旋转。
The ComboBox is not being updated because the thread created to run the update method is attempting to update a visual control belonging to another thread. In most cases this would throw an error, however here it does not.
I solved this problem by first creating a method, separate from update, that only handles the addition of COM port names to the data source. Within this method is an if statement checking if an invoke is required:
If an invoke is required, the method is called within the correct thread via a delegate:
This causes the ComboBox to be updated as new COM ports are detected by the continuous execution of the update method. A similar method can be written to remove COM ports that have been disconnected from the system. Just don't forget to end the thread when the form closes or else it will spin infinitely.