2

下面的代码执行 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;
        }
    }
}

提前谢谢了!

4

0 回答 0