C#读取计算机串口
时间:2010-10-29 来源:程雨轩
方法一:从计算机注册表的特定位置读取出串口信息。
/// <summary>
/// 从注册表获取系统串口列表
/// </summary>
public string[] GetComList()
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
string[] sSubKeys = keyCom.GetValueNames();
string[] str = new string[sSubKeys.Length];
for (int i = 0; i < sSubKeys.Length; i++)
{
str[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return str;
}
方法二:利用.NET下提供的SerialPort类具体如下:
void GetPort()
{
Microsoft.Win32.RegistryKey hklm= Microsoft.Win32.Registry.LocalMachine;
Microsoft.Win32.RegistryKey software11= hklm.OpenSubKey("HARDWARE");
//打开"HARDWARE"子健
Microsoft.Win32.RegistryKey software= software11.OpenSubKey("DEVICEMAP");
Microsoft.Win32.RegistryKey sitekey= software.OpenSubKey("SERIALCOMM");
//获取当前子健
String []Str2= sitekey.GetValueNames;
//Str2=System.IO.Ports.SerialPort.GetPortNames();//第二中方法,直接取得串口值
//获得当前子健下面所有健组成的字符串数组
Integer ValueCount= sitekey.ValueCount;
//获得当前子健存在的健值
int i;
for( i=0;i< ValueCount;i++)
{
ComboBox1.Items.Add(sitekey.GetValue(Str2[i]));
}
}