7

如下所示,我能够通过给定的 pid 和 vid 获取连接到 32 位 win7OS 机器的 USB com 端口名称,但是在 x64 中运行时它卡在以下行:

comports.Add((string)rk6.GetValue("PortName"));

这是我的代码

static List<string> ComPortNames(String VID, String PID)
    {
        String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
        Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();

        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");

        foreach (String s3 in rk2.GetSubKeyNames())
        {

            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        comports.Add((string)rk6.GetValue("PortName"));
                    }
                }
            }
        }
        return comports;
    }

实际代码在这里,那么如何在 x64 中获取 com 端口名称,有什么建议吗?

4

5 回答 5

9

当我在 Windows 10 x64 下测试Youkko的答案时,我得到了一些奇怪的结果,并查看了我机器上的注册表,这些LocationInformation键包含字符串,例如Port_#0002.Hub_#0003它们与设备连接的 USB 集线器/端口相关,而不是 COM Windows 分配的端口。

所以在我的情况下,我得到了 COM2,它是我主板上的一个硬件端口,它跳过了我期望的 COM5 端口,但它位于PortName注册表项下。我不确定自您使用的 Windows 版本以来是否发生了某些变化,但我认为您的主要问题可能是没有检查键上的空值。

以下稍作修改的版本似乎可以在各种 Windows 7 / 10 和 x32 / 64 系统上正常工作,我还添加了一个检查SerialPort.GetPortNames()以确保设备可用并在返回之前插入系统:

static List<string> ComPortNames(String VID, String PID)
{
    String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
    Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
    List<string> comports = new List<string>();

    RegistryKey rk1 = Registry.LocalMachine;
    RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");

    foreach (String s3 in rk2.GetSubKeyNames())
    {
        RegistryKey rk3 = rk2.OpenSubKey(s3);
        foreach (String s in rk3.GetSubKeyNames())
        {
            if (_rx.Match(s).Success)
            {
                RegistryKey rk4 = rk3.OpenSubKey(s);
                foreach (String s2 in rk4.GetSubKeyNames())
                {
                    RegistryKey rk5 = rk4.OpenSubKey(s2);
                    string location = (string)rk5.GetValue("LocationInformation");
                    RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                    string portName = (string)rk6.GetValue("PortName");
                    if (!String.IsNullOrEmpty(portName) && SerialPort.GetPortNames().Contains(portName))
                        comports.Add((string)rk6.GetValue("PortName"));
                }
            }
        }
    }
    return comports;
}
于 2016-01-21T08:13:35.313 回答
7

通过阅读您的代码,我发现您在注册表中查看的当前路径不包含任何有关端口的信息。但我找到了一种通过做这个小改动来阅读它的方法:

    static List<string> ComPortNames(String VID, String PID)
    {
        String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
        Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();

        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");

        foreach (String s3 in rk2.GetSubKeyNames())
        {

            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        string location = (string)rk5.GetValue("LocationInformation");
                        if (!String.IsNullOrEmpty(location))
                        {
                            string port = location.Substring(location.IndexOf('#') + 1, 4).TrimStart('0');
                            if (!String.IsNullOrEmpty(port)) comports.Add(String.Format("COM{0:####}", port));
                        }
                        //RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        //comports.Add((string)rk6.GetValue("PortName"));
                    }
                }
            }
        }
        return comports;
    }

它确实工作得很好。顺便说一句,谢谢您的代码……它对我帮助很大!

于 2012-08-27T14:22:44.730 回答
4

这是我对此的看法(即使它不是直接的 A 到 Q)

  • USB 设备总是(并且总是)在(最后的HKLM\SYSTEM\CurrentControlSet\Enum\USB注释)下枚举USB
    • 设备节点的格式VID_xxxx&PID_xxxx*xxxx十六进制,末尾可能有一些额外的函数数据
    • 每个设备节点都有一个基于序列号或设备和功能的其他数据的子标识符节点
    • 标识符节点可以具有"FriendlyName"有时在括号中包含 COM 的值,例如“虚拟串行端口 (COM6)”
    • 结果路径:HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_xxxx&PID_xxxx*\*\Device Parameters\具有命名的值"PortName"
  • 当前可用的 com 端口由System.IO.Ports.SerialPort.GetPortNames()
  • OpenSubKey工具IDisposable,应该有using.Dispose()在他们身上

    using System.IO.Ports;
    using System.Linq;
    using Microsoft.Win32;
    
    public class UsbSerialPort
    {
        public readonly string PortName;
        public readonly string DeviceId;
        public readonly string FriendlyName;
    
        private UsbSerialPort(string name, string id, string friendly)
        {
            PortName = name;
            DeviceId = id;
            FriendlyName = friendly;
        }
    
        private static IEnumerable<RegistryKey> GetSubKeys(RegistryKey key)
        {
            foreach (string keyName in key.GetSubKeyNames())
                using (var subKey = key.OpenSubKey(keyName))
                    yield return subKey;
        }
    
        private static string GetName(RegistryKey key)
        {
            string name = key.Name;
            int idx;
            return (idx = name.LastIndexOf('\\')) == -1 ?
                name : name.Substring(idx + 1);
        }
    
        public static IEnumerable<UsbSerialPort> GetPorts()
        {
            var existingPorts = SerialPort.GetPortNames();
            using (var enumUsbKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\USB"))
            {
                if (enumUsbKey == null)
                    throw new ArgumentNullException("USB", "No enumerable USB devices found in registry");
                foreach (var devBaseKey in GetSubKeys(enumUsbKey))
                {
                    foreach (var devFnKey in GetSubKeys(devBaseKey))
                    {
                        string friendlyName =
                            (string) devFnKey.GetValue("FriendlyName") ??
                            (string) devFnKey.GetValue("DeviceDesc");
                        using (var devParamsKey = devFnKey.OpenSubKey("Device Parameters"))
                        {
                            string portName = (string) devParamsKey?.GetValue("PortName");
                            if (!string.IsNullOrEmpty(portName) &&
                                existingPorts.Contains(portName))
                                yield return new UsbSerialPort(portName, GetName(devBaseKey) + @"\" + GetName(devFnKey), friendlyName);
                        }
                    }
    
                }
            }
        }
    
        public override string ToString()
        {
            return string.Format("{0} Friendly: {1} DeviceId: {2}", PortName, FriendlyName, DeviceId);
        }
    }
    
于 2016-09-07T19:39:03.293 回答
2

我认为ManagementObjectSearcher可能是比直接读取注册表更好的方法。

这是虚拟 COM 端口的示例

于 2012-04-27T12:51:00.817 回答
2

好的,使用 ManagementObjectSearcher(如果存在,它会提供 COM 端口索引和 VID 和 PID):

        List < List <string>> USBCOMlist = new List<List<string>>();
        try
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                if (queryObj["Caption"].ToString().Contains("(COM"))
                {
                    List<string> DevInfo = new List<string>();

                    string Caption = queryObj["Caption"].ToString();
                    int CaptionIndex = Caption.IndexOf("(COM");
                    string CaptionInfo = Caption.Substring(CaptionIndex + 1).TrimEnd(')'); // make the trimming more correct                 

                    DevInfo.Add(CaptionInfo);

                    string deviceId = queryObj["deviceid"].ToString(); //"DeviceID"

                    int vidIndex = deviceId.IndexOf("VID_");
                    int pidIndex = deviceId.IndexOf("PID_");
                    string vid = "", pid = "";

                    if (vidIndex != -1 && pidIndex != -1)
                    {
                        string startingAtVid = deviceId.Substring(vidIndex + 4); // + 4 to remove "VID_"                    
                        vid = startingAtVid.Substring(0, 4); // vid is four characters long
                                                             //Console.WriteLine("VID: " + vid);
                        string startingAtPid = deviceId.Substring(pidIndex + 4); // + 4 to remove "PID_"                    
                        pid = startingAtPid.Substring(0, 4); // pid is four characters long
                    }

                    DevInfo.Add(vid);
                    DevInfo.Add(pid);

                    USBCOMlist.Add(DevInfo);
                }

            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show(e.Message);
        }
于 2016-11-21T12:55:37.263 回答