RegCloseKey Function

Closes a handle to an open registry key.

Syntax

LONG RegCloseKey(
  HKEY hKey
);

Parameters

Parameter Description
hKey A handle to the open registry key that is to be closed.
This handle must have been opened by a function such as RegOpenKeyEx or RegCreateKeyEx.

Return Value

If the function succeeds, the return value is ERROR_SUCCESS.
If the function fails, the return value is a non-zero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a more specific description of the error.

Return Code Description
ERROR_SUCCESS The operation was successful.
ERROR_INVALID_HANDLE The specified handle is invalid.
ERROR_BAD_ENVIRONMENT The registry is in an inconsistent state.

Remarks

The handle specified by the hKey parameter is invalidated upon return from this function, even if the function returns an error. Therefore, you should not use the handle again after calling RegCloseKey.

It is important to close registry keys when you are finished with them to free up system resources. Failure to do so can lead to registry leaks and performance degradation.

Example

// Example demonstrating RegCloseKey usage
#include <windows.h>
#include <iostream>

int main() {
    HKEY hKey;
    LONG result;

    // Open a registry key (e.g., SOFTWARE\Microsoft)
    result = RegOpenKeyEx(
        HKEY_CURRENT_USER,
        TEXT("SOFTWARE\\Microsoft"),
        0,
        KEY_READ,
        &hKey);

    if (result == ERROR_SUCCESS) {
        std::wcout << TEXT("Registry key opened successfully.") << std::endl;

        // Perform operations with the key...

        // Close the registry key
        result = RegCloseKey(hKey);

        if (result == ERROR_SUCCESS) {
            std::wcout << TEXT("Registry key closed successfully.") << std::endl;
        } else {
            std::wcerr << TEXT("Error closing registry key. Code: ") << result << std::endl;
        }
    } else {
        std::wcerr << TEXT("Error opening registry key. Code: ") << result << std::endl;
    }

    return 0;
}

Requirements

Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header Winreg.h (include Windows.h)
Library Advapi32.lib
DLL Advapi32.dll

See Also