Home >Backend Development >C++ >How to Retrieve Registry Key and Value in C ?
To safely check for the existence of a registry key, use RegOpenKeyExW with the KEY_READ access flag. If the function returns ERROR_SUCCESS, the key exists.
<code class="pseudo-code">if (key exists) { get default value of key get string value of key get DWORD value of key }</code>
<code class="cpp">#include <windows.h> int main() { // Open the registry key HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\Perl", 0, KEY_READ, &hKey); // Check if the key exists bool bExistsAndSuccess = (lRes == ERROR_SUCCESS); // Get the default value of the key std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); return 0; } // Function to get a string value from the registry 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; }</code>
The above is the detailed content of How to Retrieve Registry Key and Value in C ?. For more information, please follow other related articles on the PHP Chinese website!