Home  >  Article  >  Backend Development  >  How to Retrieve Registry Key and Value in C ?

How to Retrieve Registry Key and Value in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 03:47:02134browse

How to Retrieve Registry Key and Value in C  ?

How to Retrieve Registry Key and Value

Determining Key Existence

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.

Getting Key Value

Pseudo-Code

<code class="pseudo-code">if (key exists) {
    get default value of key
    get string value of key
    get DWORD value of key
}</code>

Example 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn