Reputation: 41
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.
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();
}
}
Upvotes: 0
Views: 1771
Reputation: 300
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.
Upvotes: 1