C# 获取计算机串口列表
C# 获取计算机串口列表功能实现。
第一步:引入库文件:"kernel32.dll"
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
第二步:获取串口列表(两种方法)
方法一:从计算机注册表的特定位置读取出串口信息。返回:从注册表获取系统串口列表
public static string[] GetComList()
{
try
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
#if TEST
OutputDebugString(keyCom.ToString());
#endif
string[] sSubKeys = keyCom.GetValueNames();
string[] rtn = new string[sSubKeys.Length];
for (int i = 0;
i < sSubKeys.Length;
i++)
{
rtn[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return rtn;
}
catch (Exception e)
{
#if TEST
OutputDebugString(e.Message);
#endif
return null;
}
}
方法二:利用.NET下提供的SerialPort类具体如下
public static string[] GetPort()
{
try
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey software11 = hklm.OpenSubKey("HARDWARE");
//打开"HARDWARE"子健
RegistryKey software = software11.OpenSubKey("DEVICEMAP");
RegistryKey sitekey = software.OpenSubKey("SERIALCOMM");
#if TEST
OutputDebugString(sitekey.ToString());
#endif
//获取当前子健
String[] Str2 = sitekey.GetValueNames();
//获得当前子健下面所有健组成的字符串数组
int ValueCount = sitekey.ValueCount;
//获得当前子健存在的健值
int i;
string[] rtn = new string[ValueCount];
for (i = 0;
i < ValueCount;
i++)
{
rtn[i] = (string)sitekey.GetValue(Str2[i]);
}
return rtn;
}
catch (Exception e)
{
#if TEST
OutputDebugString(e.Message);
#endif
return null;
}
}
【C# 获取计算机串口列表】
推荐阅读
- ACSL|ACSL 美国计算机科学联赛 2016-2017 R4 摩天大楼-Skyscraper 题解
- EditText默认不获取焦点弹出键盘
- whlie循环和for循环的应用
- 【实用教程】4种获取无水印视频素材的方法
- 插件化无法获取或找到.so文件
- 历史上的今天|【历史上的今天】2 月 16 日(世界上第一个 BBS 诞生;中国计算机教育开端;IBM 机器人赢得智能竞赛)
- 计算机网络基础TCP\HTTP\HTTPS
- 获取知识的门槛
- 计算机网络|计算机网络——DHCP协议详解
- 提取ipa|提取ipa 包内资源