WMI查询显示单个USB串行COM端口?

时间:2012-08-15 10:57:23

标签: c# usb serial-port wmi

下面的代码执行WMI查询以枚举我的计算机上的工作设备(操作系统是Windows 7)。当我有几个设备连接到USB插头时,它会检索一个USB串行端口。因此,我对这个主题有三个问题:

1)所有USB插头是否都有单独的com端口或是否有一个用于所有USB的com端口?

2)如果我将一串字符串发送到USB串口,它将如何到达特定设备?

3)我可以从此查询中提取USB端口以将其保留为字符串吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Windows.Forms;

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass x = new MyClass();
            var com = x.GetCOMs();
            foreach (string port in com) 
            {
                Console.WriteLine(port);
            }
            Console.ReadLine();
        }

    }

    class MyClass
    {
        public List<string> GetCOMs()
        {
            List<string> coms = new List<string>();
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");

                foreach (ManagementObject obj in searcher.Get())
                {
                    object captionObj = obj["Caption"];
                    if (captionObj != null)
                    {
                        string caption = captionObj.ToString();
                        if (caption.Contains("(COM"))
                        {
                            coms.Add(caption);
                        }
                    }
                }

                m_ParseCOMs(ref coms);
            }
            catch (ManagementException ex)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
                return coms;
            }

            return coms;
        }

        private void m_ParseCOMs(ref List<string> comPorts)
        {
            string[] temp;
            List<string> temp2 = new List<string>();
            int index = 0;
            foreach (string s in comPorts)
            {
                string temp3 = "";
                temp = s.Split(' ');
                temp3 += temp[temp.Length - 1] + " - ";
                for (int i = 0; i < temp.Length - 1; i++)
                {
                    temp3 += temp[i] + " ";
                }
                temp2.Insert(index, temp3);
                index++;
            }
            comPorts = temp2;
        }
    }
}

非常感谢提前!

0 个答案:

没有答案