程式筆記
C#
C# 用VID和PID自動連線serialport
K
kidneyweakx
April 28, 2020 (Updated: December 17, 2025)
原本C#的serial port function官方範例 ,是類似這樣的
C#
streamport = new SerialPort("COM3", bauadrate);
這種方法每次開啟都還要再去跟改port相當的麻煩,所以就找了別人針對windows寫的function,再返回靜態的port string給SerialPort,效果相當好。
C#
// 有錯誤可能是你沒有 using Microsoft.Win32;或其他lib
public static List<string> ComPortNames(String VID, String PID)
{
// 讀取PID和VID
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"));
// 獲取port name,如有多個相同設備,加入comports array
}
}
}
}
return comports;
}
完整內容可參照下方連結😁
code來源
Related Articles
→
LOG-DC6
No File is an Island: Unraveling Swift Dependencies and Architecture
> > In the world of Swift, we are accustomed to the power of Xcode and clean syntax. However, as a project's scale grows, an invisible monster begins to haunt the...
[程式筆記][Swift]
@kidneyweakx→
LOG-FE5
Saved by the Logs: How to Recover a Forgotten Keystore Password via IDE Build Logs.
> > The greatest distance in the world is when the password is right in the IDE, but I can't see it
[程式筆記][Android]
@kidneyweakx→
LOG-912
Hexo升級V5排除疑難雜症
> 因為剛好把電腦重灌,然後這個blog就躺在D槽等著我幫他換新的環境,然後他就被我快樂的升級了。
[程式筆記][Javascript][hexo]
@kidneyweakx