我終於整理出了這自己前幾天。有兩個部分,一個檢查註冊表,另一個檢查設備的vid/pid。
我使用的註冊表方法只是爲了確保我不捕獲像com0com這樣的null調制解調器仿真程序。
/// <summary>
/// Removes any comm ports that are not explicitly defined as allowed in ALLOWED_TYPES
/// </summary>
/// <param name="allPorts">reference to List that will be checked</param>
/// <returns></returns>
private static void nullModemCheck(ref List<string> allPorts)
{
// Open registry to get the COM Ports available with the system
RegistryKey regKey = Registry.LocalMachine;
// Defined as: private const string REG_COM_STRING ="HARDWARE\DEVICEMAP\SERIALCOMM";
regKey = regKey.OpenSubKey(REG_COM_STRING);
Dictionary<string, string> tempDict = new Dictionary<string, string>();
foreach (string p in allPorts)
tempDict.Add(p, p);
// This holds any matches we may find
string match = "";
foreach (string subKey in regKey.GetValueNames())
{
// Name must contain either VCP or Seial to be valid. Process any entries NOT matching
// Compare to subKey (name of RegKey entry)
if (!(subKey.Contains("Serial") || subKey.Contains("VCP")))
{
// Okay, this might be an illegal port.
// Peek in the dictionary, do we have this key? Compare to regKey.GetValue(subKey)
if(tempDict.TryGetValue(regKey.GetValue(subKey).ToString(), out match))
{
// Kill it!
allPorts.Remove(match);
// Reset our output string
match = "";
}
}
}
regKey.Close();
}
的VID/PID部分從techinpro
/// <summary>
/// Compile an array of COM port names associated with given VID and PID
/// </summary>
/// <param name="VID">string representing the vendor id of the USB/Serial convertor</param>
/// <param name="PID">string representing the product id of the USB/Serial convertor</param>
/// <returns></returns>
private static List<string> getPortByVPid(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;
}
串口收集它不是USB端口,只是COM端口。 – 2013-02-20 23:00:10
[需要知道設備是有線串行還是藍牙]可能的重複(http://stackoverflow.com/questions/3659939/need-to-know-whether-a-device-is-wired-serial-or-藍牙) – 2013-02-20 23:21:18
要添加一些額外的信息:當我寫這篇文章我雖然你hade打開端口/連接recive供應商ID或設備ID。我正在爲Windows編寫此代碼,通過這樣做我應該從Windows註冊表中收集這類信息。我試圖讓一個可以找到合適的設備然後運行的代碼。 – Christian 2013-02-22 16:21:38