Registry Access Samples (C++)
This section provides C++ code examples demonstrating how to access and manipulate the Windows Registry.
Basic Read Operation
This sample shows how to open a registry key and read a string value.
#include <windows.h>
#include <iostream>
int main() {
HKEY hKey;
LONG result = RegOpenKeyEx(
HKEY_CURRENT_USER,
TEXT("Software\\MyApplication"),
0,
KEY_READ,
&hKey
);
if (result == ERROR_SUCCESS) {
TCHAR valueBuffer[256];
DWORD bufferSize = sizeof(valueBuffer);
DWORD type;
result = RegQueryValueEx(
hKey,
TEXT("SettingName"),
NULL,
&type,
(LPBYTE)valueBuffer
);
if (result == ERROR_SUCCESS && type == REG_SZ) {
std::wcout << TEXT("SettingName: ") << valueBuffer << std::endl;
} else {
std::wcerr << TEXT("Failed to query registry value or type mismatch.") << std::endl;
}
RegCloseKey(hKey);
} else {
std::wcerr << TEXT("Failed to open registry key.") << std::endl;
}
return 0;
}
Basic Write Operation
This sample demonstrates how to create or update a registry value.
#include <windows.h>
#include <iostream>
int main() {
HKEY hKey;
DWORD disposition;
LONG result = RegCreateKeyEx(
HKEY_CURRENT_USER,
TEXT("Software\\MyApplication"),
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
NULL,
&hKey,
&disposition
);
if (result == ERROR_SUCCESS) {
TCHAR valueData[] = TEXT("NewValue");
result = RegSetValueEx(
hKey,
TEXT("AnotherSetting"),
0,
REG_SZ,
(CONST BYTE*)valueData,
(DWORD)sizeof(valueData)
);
if (result == ERROR_SUCCESS) {
std::wcout << TEXT("Successfully wrote registry value.") << std::endl;
} else {
std::wcerr << TEXT("Failed to write registry value.") << std::endl;
}
RegCloseKey(hKey);
} else {
std::wcerr << TEXT("Failed to create/open registry key.") << std::endl;
}
return 0;
}
Important Considerations:
- Always use proper error checking with the return values of the Registry API functions.
- Use `TEXT()` macro for string literals to ensure compatibility with both ANSI and Unicode builds.
- Be cautious when writing to the registry, especially in system-wide locations, as incorrect modifications can impact system stability.
- Consider using the Windows Registry Filter API for more advanced scenarios.