C#获取COM端口列表(完整代码)
比较与分析
获取COM端口列表的方法有多种,如从设备管理器获取(使用 setupapi.dll 中 SetupDiGetClassDevs 接口)、读取注册表(使用Registry.LocalMachine.OpenSubKey(@“HARDWARE\DEVICEMAP\SERIALCOMM”, false))等。
其中,编写设备管理器获取的代码时,在海搜得到的代码基础上,又做了一番资料查找与实践,才终于写成,所以笔者把最终的所有代码贴在本文,希望帮助到更多的人。
方法 | 优点 | 缺点 |
---|---|---|
设备管理器 | 更新快,可以方便地获取到硬件ID、友好名称等信息 | 当PC出现某些异常时,设备管理器中可能不显示COM数字(如下图),则无法区分COM端口 |
注册表 | 注册表中一直有COM数字的信息 | 获取硬件ID等信息有点麻烦 |
设备管理器中正常的端口显示:
设备管理器中异常的端口显示:
没有“(COMx)”的显示,全部是USB Serial Port,设备管理器中也找不到友好名称一项
设备管理器方法
完整代码
一些常量,不是都用到了
private const int DIGCF_ALLCLASSES = 0x00000004;
private const int DIGCF_PRESENT = 0x00000002;
//包含设备说明的REG_SZ字符串
private const int SPDRP_DEVICEDESC = 0x00000000;
//包含设备硬件 ID 列表的REG_MULTI_SZ字符串
private const int SPDRP_HARDWAREID = 0x00000001;
//包含设备的友好名称的REG_SZ字符串
private const int SPDRP_FRIENDLYNAME = 0x0000000C;
//设备的总线类型的 GUID
private const int SPDRP_BUSTYPEGUID = 0x00000013;
private const int INVALID_HANDLE_VALUE = -1;
private const int MAX_DEV_LEN = 1000;
一些引用
[DllImport("setupapi.dll", SetLastError = true)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, UInt32 iEnumerator, IntPtr hParent, UInt32 nFlags);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiEnumDeviceInfo(IntPtr lpInfoSet, UInt32 dwIndex, SP_DEVINFO_DATA devInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiGetDeviceRegistryProperty(IntPtr lpInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property, UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);
[DllImport("Kernel32.dll")]
public extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
一些次要函数,放上去就行
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
//SP_DEVINFO_DATA结构的大小(以字节为单位)
public int cbSize;
//设备的安装类的 GUID
public Guid classGuid;
//设备实例的不透明句柄 (也称为 开发节点) 的句柄
public int devInst;
//保留,仅限内部使用
public ulong reserved;
};
public static string GetSysErrMsg(int errCode)
{
IntPtr tempptr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr);
return msg;
}
主角
//函数返回值类型List<string>可自行修改
public static List<string> GetComList()
{
List<string> HWList = new List<string>();
string friendlyName;
int index;
string comName;
try
{
Guid myGUID = System.Guid.Empty;
IntPtr hDevInfo = SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, DIGCF_ALLCLASSES | DIGCF_PRESENT);
if (hDevInfo.ToInt64() == INVALID_HANDLE_VALUE)
{
//得到了错误的句柄,调用api获得错误信息
int errCode = Marshal.GetLastWin32Error();
throw new Exception(GetSysErrMsg(errCode));
}
//SP_DEVINFO_DATA在次要函数中已经定义
SP_DEVINFO_DATA DeviceInfoData;
//感兴趣可以查一下SP_DEVINFO_DATA的说明
DeviceInfoData = new SP_DEVINFO_DATA();
//⭐重点1,区分32位系统和64位系统,但为什么是这两个值,
//笔者也是根据其他资料得到的,不知原理
if (Environment.Is64BitOperatingSystem)
DeviceInfoData.cbSize = 32;
else
DeviceInfoData.cbSize = 28;
DeviceInfoData.devInst = 0;
//使用Empty即可
DeviceInfoData.classGuid = System.Guid.Empty;
DeviceInfoData.reserved = 0;
UInt32 i = 0;
//注意是使用StringBuilder类型
StringBuilder DeviceName = new StringBuilder("");
//设置StringBuilder的容量
DeviceName.Capacity = MAX_DEV_LEN;
//⭐重点2,这个while内的写法
while (SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData))
{
i++;
//⭐重点3,这个函数传入的参数,此处用SPDRP_FRIENDLYNAME查友好名称
if (!SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, SPDRP_FRIENDLYNAME, 0,
DeviceName, MAX_DEV_LEN, IntPtr.Zero))
{
int errCode = Marshal.GetLastWin32Error();
continue;
}
if (!DeviceName.ToString().Contains("(COM"))
{
continue;
}
friendlyName = DeviceName.ToString();
//只取出COM号
index = friendlyName.IndexOf("(COM");
comName = friendlyName.Substring(index + 1, friendlyName.Length - index - 2);
HWList.Add(comName);
}
//⭐重点4,这个函数一定要在最后调用
//删除设备信息集并释放所有关联的内存
SetupDiDestroyDeviceInfoList(hDevInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
int errCode = Marshal.GetLastWin32Error();
throw new Exception(GetSysErrMsg(errCode));
}
return HWList;
}
至此,所有代码均已呈现
延申:选出特定硬件ID的端口
主角部分修改为:
public static string SelectHardwareID(string hardID)
{
string friendlyName;
int index;
string comName = "Null";
try
{
Guid myGUID = System.Guid.Empty;
IntPtr hDevInfo = SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, DIGCF_ALLCLASSES | DIGCF_PRESENT);
if (hDevInfo.ToInt64() == INVALID_HANDLE_VALUE)
{
int errCode = Marshal.GetLastWin32Error();
throw new Exception(GetSysErrMsg(errCode));
}
SP_DEVINFO_DATA DeviceInfoData;
DeviceInfoData = new SP_DEVINFO_DATA();
if (Environment.Is64BitOperatingSystem)
DeviceInfoData.cbSize = 32;
else
DeviceInfoData.cbSize = 28;
DeviceInfoData.devInst = 0;
DeviceInfoData.classGuid = System.Guid.Empty;
DeviceInfoData.reserved = 0;
UInt32 i = 0;
StringBuilder DeviceName = new StringBuilder("");
DeviceName.Capacity = MAX_DEV_LEN;
StringBuilder DeviceHardWareID = new StringBuilder();
DeviceHardWareID.Capacity = MAX_DEV_LEN;
//将传入的string类型转为StringBuilder,方便之后比较
StringBuilder id = new StringBuilder(hardID);
while (SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData))
{
i++;
//先根据友好名称筛选,选出需要的USB设备
if (!SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, SPDRP_FRIENDLYNAME, 0,
DeviceName, MAX_DEV_LEN, IntPtr.Zero))
{
int errCode = Marshal.GetLastWin32Error();
continue;
}
if (!DeviceName.ToString().Contains("(COM"))
{
continue;
}
//⭐之后再调用一次SetupDiGetDeviceRegistryProperty,
//传入参数改为SPDRP_HARDWAREID
if (!SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, SPDRP_HARDWAREID, 0, DeviceHardWareID, MAX_DEV_LEN, IntPtr.Zero))
{
continue;
}
if (DeviceHardWareID.Equals(id))
{
friendlyName = DeviceName.ToString();
index = friendlyName.IndexOf("(COM");
comName = friendlyName.Substring(index + 1, friendlyName.Length - index - 2);
break;
}
}
//依旧要记得调用Destroy
SetupDiDestroyDeviceInfoList(hDevInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
int errCode = Marshal.GetLastWin32Error();
throw new Exception(GetSysErrMsg(errCode));
}
return comName;
}
注册表方法
win+R,输入regedit,打开注册表
COM信息位于LocalMachine下,HARDWARE\DEVICEMAP\SERIALCOMM
public string[] GetPortNames()
{
using (RegistryKey local = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false)) {
if (local == null) return new string[0];
string[] k = local.GetValueNames();
if (k.Length > 0) {
string[] ports = new string[local.ValueCount];
for (int i = 0; i < k.Length; i++) {
ports[i] = local.GetValue(k[i]) as string;
}
return ports;
}
return new string[0];
}
}
关于从注册表中获取硬件ID:
根据MSDN中USB 设备注册表项的说明,通过设备的VID与PID,可以找到设备的友好名称、硬件ID的信息,但实际应用中,注册表同一VID PID下有多个子项,并不像MSDN示例(下图)中那么简洁,于是笔者就,,知难而退了ヾ(•ω•`)o
感谢阅读本文!如有错误,烦请指出!