如何从Windows注册表读取值
时间:2020-03-05 18:44:52 来源:igfitidea点击:
给定某个注册表值的键(例如HKEY_LOCAL_MACHINE \ blah \ blah \ blah \ foo),我该如何:
- 安全地确定存在这样的密钥。
- 以编程方式(即使用代码)获得其价值。
我绝对不打算将任何内容写回注册表(如果可以的话,在我职业生涯的整个过程中)。因此,如果我不正确地写入注册表,我们可以跳过有关光速爆炸的体内每个分子的讲座。
首选使用C ++的答案,但是大多数情况下,我们只需要知道要获得该值的特殊Windows API含义是什么。
解决方案
回答
RegQueryValueEx
如果值存在,则给出值;如果键不存在,则返回错误代码ERROR_FILE_NOT_FOUND。
(我无法确定我的链接是否有效,但是如果我们只是用谷歌搜索" RegQueryValueEx",则第一个匹配项是msdn文档。)
回答
RegOpenKey和RegQueryKeyEx对将解决问题。
如果使用MFC,则CRegKey类是更简单的解决方案。
回答
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
回答
这是一些伪代码,用于检索以下内容:
- 如果注册表项存在
- 该注册表项的默认值是多少
- 什么是字符串值
- 什么是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<LPBYTE>(&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; }