基于VID / PID,虚拟Com端口不正确

时间:2015-09-02 06:06:41

标签: c# pid

我正在开发一个usb cdc自定义应用程序,用于根据vid和pid获取com端口名称。我使用下面的代码,但它没有返回正确的com端口名称。

以下代码输出(Com4),但Com6和Com4上检测到的设备不存在。

public  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 (location != string.Empty)
          {
            string port = location.Substring(location.IndexOf('#') + 1, 4).TrimStart('0');
            if (port != string.Empty) comports.Add(String.Format("COM{0:####}", port));
          }
          //RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
          //comports.Add((string)rk6.GetValue("PortName"));
        }
      }
    }
  }
  return comports;
}

private void Get_Port_Name_Click(object sender, EventArgs e)
{ 
  var list = ComPortNames("0000", "0400");
}

0 个答案:

没有答案