I'm currently working on a little C# program to interact with an Arduino microcontroller. The program has a combobox where you can choose the COM-port. The μc is connected by USB and a virtual COM-port (CH340).
I use the code below to fill in the avaible COM-ports to the combobox.
private void Form1_Load(object sender, EventArgs e)
{
string[] PortNames = SerialPort. GetPortNames();
comboBoxPort.Items.AddRange(PortNames);
}
The downside of this is, you have to take a look into the Device Manager to see which one is the correct one for the μc. My PC for example has 4 active COM-ports, one physical, 2 virtual and another virtual one for the μc. What I'm searching for is a way to display the complete Name of the device with the associated COM-port (like you can find it in the Device Manager)
COM-ports in the Device Manager
After a bit of research I found out that there is another possibility by using the WMI. After a lot of testing with the "WMI Code Creator" I don't know what else I can try to accomplish what I’ve attended to do. All the namespaces and classes I’ve tried are only generating the COM-port like COM1, COM2… or they generate the hardware-id which is not useful for the user of the program.
The code below is more or less exactly what I'm searching for but it only works for “real” build in COM-ports.
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\CIMV2",
"SELECT * FROM Win32_SerialPort");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_SerialPort instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Name: {0}", queryObj["Name"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
Is there any other possible way to get a list of all the COM-ports like there is one insinde of the Device Manager? Is it maybe possible to use the hardware-id of the devices to identify them somehow and then, in a second step get the correct name for them?
I would be very pleased if I could get some help with this. There must be a way to do this but I can't find it.
And sry for my english if something sounds wierd :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…