在以下代码中,GetAge()
将返回您的键值,如果键不存在,则返回 null。
[DllImport("Advapi32.dll")]
static extern uint RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, out int phkResult);
[DllImport("Advapi32.dll")]
static extern uint RegCloseKey(int hKey);
[DllImport("advapi32.dll", EntryPoint = "RegQueryValueEx")]
public static extern int RegQueryValueEx(int hKey, string lpValueName, int lpReserved, ref uint lpType, System.Text.StringBuilder lpData, ref uint lpcbData);
public const int KEY_QUERY_VALUE = 0x0001;
public const int KEY_WOW64_64KEY = 0x0100;
static public string GetAge()
{
string EPG_REGKEY = @"SOFTWARE\Test\MyParameters";
UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
int hkey = 0;
try
{
uint lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, EPG_REGKEY, 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, out hkey);
if (0 != lResult) return null;
uint lpType = 0;
uint lpcbData = 1024;
StringBuilder AgeBuffer = new StringBuilder(1024);
RegQueryValueEx(hkey, "Age", 0, ref lpType, AgeBuffer, ref lpcbData);
string Age = AgeBuffer.ToString();
return Age;
}
finally
{
if (0 != hkey) RegCloseKey(hkey);
}
}