使用 VID 和 PID 识别连接到 x64 的 USB 设备的 COM 端口 [英] Identify COM port using VID and PID for USB device attached to x64
问题描述
如下所示,我可以通过给定的 pid 和 vid 获取连接到 32 位 win7OS 机器的 USB com 端口名称,但是在 x64 中运行时,它卡在以下行中:
As following i able to get usb com port names attached to 32bit win7OS machine, by given pid and vid,but when running in x64 it stuck in the following line:
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 端口名称,有什么建议吗?
actual code get here, So how to get com port names in x64, any suggestion?
推荐答案
通过阅读您的代码,我发现您在注册表中查看的当前路径不包含任何有关端口的信息.但是我通过做这个小改动找到了一种阅读方式:
By reading your code, I found out that the current path you're looking at in registry does not contain any information about ports. But I found a way to read it by doing this little change:
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;
}
它确实工作得很好.顺便说一句,感谢您的代码......它对我帮助很大!
It did work perfectly. Thank you for your code, by the way... It helped me a lot!
这篇关于使用 VID 和 PID 识别连接到 x64 的 USB 设备的 COM 端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!