HKEY Type
The HKEY type is used to represent a handle to a registry key.
Definition
A handle to a registry key. This type is defined as a pointer to an opaque structure.
typedef PVOID HKEY;
Or, more commonly:
typedef void* HKEY;
Remarks
The Windows Registry is a hierarchical database that stores low-level settings for the Microsoft Windows operating system and for applications that opt to use the registry instead of configuration files. The HKEY type is used extensively in the Windows API to refer to specific locations (keys) within this registry structure.
When you open a registry key using functions like RegOpenKeyEx, you are returned an HKEY value. This handle acts as a reference to the opened key and must be used in subsequent operations (like reading or writing values, or creating subkeys) that pertain to that key. It is crucial to close these handles when they are no longer needed by calling RegCloseKey to release system resources.
Commonly Used Predefined Keys
The registry has several predefined top-level keys, which are commonly accessed using their predefined constants:
HKEY_CLASSES_ROOT: Root for file associations and COM object registrations.HKEY_CURRENT_USER: Root for user-specific settings.HKEY_LOCAL_MACHINE: Root for machine-specific settings.HKEY_USERS: Root for all user profiles on the system.HKEY_CURRENT_CONFIG: Root for current hardware profile information.
Example Usage
The following C++ snippet demonstrates how to open a registry key and read a value:
#include <windows.h>
#include <iostream>
int main() {
HKEY hKey;
LONG result;
DWORD type;
char value[256];
DWORD dataSize = sizeof(value);
// Open the registry key for the current user's software settings
result = RegOpenKeyEx(
HKEY_CURRENT_USER, // Handle to an open key
TEXT("Software\\MyApp"), // Name of the subkey to open
0, // Reserved
KEY_READ, // Access rights
&hKey // Address of the handle to the open key
);
if (result == ERROR_SUCCESS) {
// Read a string value from the key
result = RegQueryValueEx(
hKey, // Handle to an open key
TEXT("SettingName"), // Name of the value to query
NULL, // Reserved
&type, // Pointer to buffer that receives the type code
(LPBYTE)value, // Pointer to the buffer that receives the data
&dataSize // Pointer to the size of the buffer
);
if (result == ERROR_SUCCESS) {
std::cout << "Value for SettingName: " << value << std::endl;
} else {
std::cerr << "Error reading registry value: " << result << std::endl;
}
// Close the key handle
RegCloseKey(hKey);
} else {
std::cerr << "Error opening registry key: " << result << std::endl;
}
return 0;
}