在 C# 中从组合框中添加/删除 COM 端口

发布于 2024-11-19 15:14:34 字数 974 浏览 0 评论 0原文

我正在尝试编写一个程序,利用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撕心裂肺的伤痛 2024-11-26 15:14:34

尝试像这样修改代码。

BindingList<String> availPorts = new BindingList<String>();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
private void Form1_Load(object sender, EventArgs e)
{

    Thread t = new Thread(new ThreadStart(update));
    t.Start();
    autoResetEvent.WaitOne();
    this.comboBox1.DataSource = availPorts;
}

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);
            }
        }

        autoResetEvent.Set();
    }
}

Try modify code like this.

BindingList<String> availPorts = new BindingList<String>();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
private void Form1_Load(object sender, EventArgs e)
{

    Thread t = new Thread(new ThreadStart(update));
    t.Start();
    autoResetEvent.WaitOne();
    this.comboBox1.DataSource = availPorts;
}

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);
            }
        }

        autoResetEvent.Set();
    }
}
陌路黄昏 2024-11-26 15:14:34

ComboBox 未更新,因为创建运行更新方法的线程正在尝试更新属于另一个线程的可视控件。在大多数情况下,这会引发错误,但这里不会。

我通过首先创建一个独立于更新的方法解决了这个问题,该方法仅处理向数据源添加 COM 端口名称。在此方法中,有一个 if 语句检查是否需要调用:

private void addPort(String port)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new addPortDelegate(addPort), port);
        }
        else
        {
            availablePorts.Add(port);
            Console.WriteLine("FOUND");
        }
    }

如果需要调用,则通过委托在正确的线程中调用该方法:

private delegate void addPortDelegate(String s);

这会导致 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:

private void addPort(String port)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new addPortDelegate(addPort), port);
        }
        else
        {
            availablePorts.Add(port);
            Console.WriteLine("FOUND");
        }
    }

If an invoke is required, the method is called within the correct thread via a delegate:

private delegate void addPortDelegate(String s);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文