鉴于某些注册表值的关键(例如HKEY_LOCAL_MACHINE\blah\blah\blah\foo)我该如何:
安全地确定存在这样的密钥.
以编程方式(即使用代码)获取其值.
我绝对没有打算将任何东西写回注册表(如果我可以提供帮助的话,我的职业生涯期间).因此,如果我错误地写入注册表,我们可以跳过关于我体内每个分子以光速爆炸的讲座.
首选C++中的答案,但大多只需要知道特殊的Windows API咒语是什么.
这是一些用于检索以下内容的伪代码:
如果存在注册表项
该注册表项的默认值是什么
什么是字符串值
什么是DWORD值
示例代码:
包含库依赖项:Advapi32.lib
HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; }
const CString REG_SW_GROUP_I_WANT = _T("SOFTWARE\\My Corporation\\My Package\\Group I want"); const CString REG_KEY_I_WANT= _T("Key Name"); CRegKey regKey; DWORD dwValue = 0; if(ERROR_SUCCESS != regKey.Open(HKEY_LOCAL_MACHINE, REG_SW_GROUP_I_WANT)) { m_pobLogger->LogError(_T("CRegKey::Open failed in Method")); regKey.Close(); goto Function_Exit; } if( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT)) { m_pobLogger->LogError(_T("CRegKey::QueryValue Failed in Method")); regKey.Close(); goto Function_Exit; } // dwValue has the stuff now - use for further processing
RegOpenKey和RegQueryKeyEx这对可以解决问题.
如果使用MFC CRegKey类则更容易解决.