简体   繁体   中英

Reading Windows Registry Key REG_BINARY in c++

I'm trying to read a registry key in c++, that's my function:

    DWORD regkey()
{
    HKEY hKey;
    DWORD dwDisp = REG_BINARY;
    DWORD dwSize = sizeof(dwDisp);
    DWORD dwValue = 0;
    DWORD dwReturn;
    DWORD dwBufSize = sizeof(dwDisp);

    if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HERE\\IS\\THE\\REGKEY",0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS)
    {
        DWORD error = RegQueryValueEx(hKey,L"key",0,0, (LPBYTE)&dwReturn, &dwBufSize);
        if(error == ERROR_SUCCESS)
        {
            return dwReturn;
        }
    }

    RegCloseKey(hKey);

    return 0;
}

but it's returning nothing... please help me.

The registry functions will return a meaningful error code, and that can help you diagnose the problem. Try holding on to that code:

{
    HKEY hKey;
    DWORD dwDisp = REG_BINARY;
    DWORD dwSize = sizeof(dwDisp);
    DWORD dwValue = 0;
    DWORD dwReturn;
    DWORD dwBufSize = sizeof(dwReturn);

    DWORD dwError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HERE\\IS\\THE\\REGKEY",0, KEY_READ, &hKey) ;
    if( dwError == ERROR_SUCCESS)
    {
        dwError = RegQueryValueEx(hKey,L"key",0,0, (LPBYTE)&dwReturn, &dwBufSize);
        if(error == ERROR_SUCCESS)
        {
            // it worked!
        }
        else
        {
            // it failed to read, check dwError for the error code
            dwResult = 0;
        }

        RegCloseKey(hKey);
    }
    else
    {
        // it failed to open, check dwError for the error code
        dwResult = 0;
    }


    return 0;
}

If you're using Visual Studio, you can break on any of the failure points and evaluate dwError,hr in your watch window. The ,hr format specifier causes the debugger to look up the error code for you and present a meaningful string that describes the problem. That should lead you to an understanding of what went wrong.

If you can tell us which function is failing and which code you're getting back from that function, we might be able to provide more detailed help. As it stands now, you've presented us with a bit of a guessing game. Maybe you've misspelled your registry key name or given an incorrect path. Your code seems to imply you're passing the registry key RegQueryValueEx() , but you're meant to pass a value name, not a key name, to that function. Maybe you have a problem with access privileges because you're looking at a protected part of the registry and not running as an account with enough rights to read that key. (And so, you should pass KEY_READ instead of KEY_ALL_ACCESS .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM