闲闲流水

获取系统枚举的值

RegEnumValue

枚举指定项的值

编辑本段返回值

Long,零(ERROR_SUCCESS)表示成功。其他任何值都代表一个错误代码

编辑本段参数表

参数 类型及说明
hKey Long,一个已打开项的句柄,或者指定一个标准项名
dwIndex Long,欲获取值的索引。注意第一个值的索引编号为零
lpValueName String,用于装载位于指定索引处值名的一个缓冲区
lpcbValueName Long,用于装载lpValueName缓冲区长度的一个变量。一旦返回,它会设为实际载入缓冲区的字符数量
lpReserved Long,未用;设为零
lpType Long,用于装载值的类型代码的变量
lpData Byte,用于装载值数据的一个缓冲区
lpcbData Long,用于装载lpData缓冲区长度的一个变量。一旦返回,它会设为实际载入缓冲区的字符数量
示例(C#):

[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int RegCloseKey(int hKey);

[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, EntryPoint = "RegOpenKeyA")]
private static extern int RegOpenKey(uint hKey, string lpSubKey, ref int phkResult);

[DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, EntryPoint = "RegEnumValueA")]
private static extern int RegEnumValue(int hKey, int dwIndex, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName,
ref int lpcbValueName, int lpReserved, int lpType, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpData, ref int lpcbData);

 

public static string[] GetSerialPortNames()
{
#region 方式一:调用系统API(DLL文件:advapi32.dll)读取注册表,并处理读取结果的“字符串结束符”
string[] ports = null;
List<string> portsList = new List<string>();
uint HKEY_LOCAL_MACHINE = 0x80000002;
int hKey = -1;
int ret = RegOpenKey(HKEY_LOCAL_MACHINE, @"Hardware\DEVICEMAP\SERIALCOMM", ref hKey);
try
{
if (ret == 0)
{
int index = 0;
int BufferSize = 255;
int ERROR_NO_MORE_ITEMS = 259;
string valueName = "".PadRight(BufferSize, ' ');
int valueNameLength = BufferSize;
int valueLength = BufferSize;
string value = "".PadRight(BufferSize, ' ');
while (RegEnumValue(hKey, index, ref valueName, ref valueNameLength, 0, 0, ref value, ref valueLength) != ERROR_NO_MORE_ITEMS)
{
if (valueLength > 0)
{
if (value[valueLength - 1] == 0)
valueLength -= 1;
portsList.Add(value.Substring(0, valueLength));
}
index += 1;
valueName = "".PadRight(BufferSize, ' ');
valueNameLength = BufferSize;
valueLength = BufferSize;
}
}
}
catch (Exception)
{
}
finally
{
if (ret == 0)
RegCloseKey(hKey);
}
if (portsList.Count == 0)
ports = new string[0];
else
ports = portsList.ToArray();
return ports;
#endregion

}

 

posted on 2013-03-16 01:33  闲闲流水  阅读(191)  评论(0编辑  收藏  举报

导航