0

I want to make a program that detects if a certain device is connected to a COM port by the device name when a button is clicked. For example, if the device is connected and it shows "HUAWEI Mobile Connect - 3G PC UI Interface (COM16)" in the device manager, say in a message box if the device is connected.

enter image description here

I have a code but it only shows the available COM port.

private void button1_Click(object sender, EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();

        foreach (string port in ports)
        {
            richTextBox1.Text = port.ToString();
        }
    }

1 Answer 1

2

If you are fine with using the System.Management NuGet package in Visual Studio, you can use the following bit of code to get your device name.

using (var devices = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
{
    string[] portnames = SerialPort.GetPortNames();
    var ports = devices.Get().Cast<ManagementBaseObject>().ToList();
    var device_list = (from n in portnames
                       join p in ports on n equals p["DeviceID"].ToString()
                       select n + " - " + p["Caption"]).ToList();
}

Here, device_list contains the names of all the devices connected to COM. You can search for a particular device by device name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.