获取系统枚举的值
RegEnumValue
编辑本段返回值
编辑本段参数表
[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
}
浙公网安备 33010602011771号