[英]WMI: Get list of all serial (COM) ports including virtual ports
我目前正在研究一個C#程序,以與Arduino微控制器進行交互。 該程序有一個組合框,您可以在其中選擇COM端口。 µc通過USB和虛擬COM端口(CH340)連接。
我使用下面的代碼將可用的COM端口填充到組合框。
private void Form1_Load(object sender, EventArgs e)
{
string[] PortNames = SerialPort. GetPortNames();
comboBoxPort.Items.AddRange(PortNames);
}
不利的一面是,您必須查看“設備管理器”以查看哪一個是適用於µc的正確方法。 例如,我的PC有4個活動的COM端口,一個為物理端口,兩個為虛擬端口,另一個為µc提供虛擬端口。 我正在尋找的是一種顯示帶有關聯COM端口的設備完整名稱的方法(就像您可以在“設備管理器”中找到它一樣)
經過一些研究,我發現使用WMI還有另一種可能性。 在使用“ WMI代碼創建器”進行了大量測試之后,我不知道我還能嘗試完成我所從事的工作。 我嘗試過的所有名稱空間和類都只生成COM端口,例如COM1,COM2…或它們生成對程序用戶沒有用的硬件ID。 下面的代碼或多或少完全是我要搜索的代碼,但僅適用於COM端口中的“真實”構建。
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);
}
}
}
}
是否還有其他可能的方法來獲取所有COM端口的列表,例如設備管理器的一個索引? 是否有可能使用設備的硬件ID以某種方式識別它們,然后在第二步中為它們獲取正確的名稱?
如果能對此有所幫助,我將感到非常高興。 一定有辦法做到這一點,但我找不到。
如果聽起來有些奇怪,請為我的英語感到抱歉:)
如前所述,這里是完整的工作代碼,可以用所有可用的COM端口填充組合框,並在選擇后設置關聯的端口。
(原始答案如何獲取端口名稱-> 鏈接 )
感謝@o_O提供的鏈接,希望有人會發現此代碼有用。
private void Form1_Load(object sender, EventArgs e)
{
// Get all serial (COM)-ports you can see in the devicemanager
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\cimv2",
"SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
// Sort the items in the combobox
CmdBoxPort.Sorted = true;
// Add all available (COM)-ports to the combobox
foreach (ManagementObject queryObj in searcher.Get())
CmdBoxPort.Items.Add(queryObj["Caption"]);
}
private void CmdBoxPort_SelectedIndexChanged(object sender, EventArgs e)
{
// Set the right port for the selected item.
// The portname is based on the "COMx" part of the string (SelectedItem)
string item = CmdBoxPort.SelectedItem.ToString();
// Search for the expression "(COM" in the "selectedItem" string
if (item.Contains("(COM"))
{
// Get the index number where "(COM" starts in the string
int indexOfCom = item.IndexOf("(COM");
// Set PortName to COMx based on the expression in the "selectedItem" string
// It automatically gets the correct length of the COMx expression to make sure
// that also a COM10, COM11 and so on is working properly.
serialPort1.PortName = item.Substring(indexOfCom + 1, item.Length - indexOfCom - 2);
}
else
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.