Home > Backend Development > C++ > body text

How to Retrieve Registry Key and Value in C ?

Linda Hamilton
Release: 2024-10-31 03:47:02
Original
133 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!