Posts Tagged ‘RegQueryValueEx’

Querying the Windows Registry

I’ve always considered the Windows Registry to be a pretty awful piece of technology and a terrible way to store system and application settings. That said, if you’re doing Windows development, you’re probably going to have to touch it at some point. I was digging through some old C++ code, and came across some code to get the current version of Flash installed on the system (I can’t remember why I need to do this at all), which I think serves a good example of how to query the registry.

#include <iostream>
#include <windows.h>

int main()
{
    LONG ret;
    HKEY result;
    
    
// open the key "HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\FlashPlayerPlugin"
    
ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Macromedia\\FlashPlayerPlugin", 0, KEY_QUERY_VALUE, &result);
    
if(ret != ERROR_SUCCESS)
        
return 1;

    
// allocate 64 wide chars to hold value
    
DWORD dataLen = 64;
    
wchar_t* data = new wchar_t[dataLen];

    
// query the value of "Version" for the key we opened
    
ret = RegQueryValueExW(result, L"Version", NULL, NULL, (LPBYTE)data, &dataLen);
    RegCloseKey(result);
    
if(ret != ERROR_SUCCESS)
        
return 2;

    
// put the value in a wide string and output it
    
std::wstring versionStr(data);
    std::wcout << versionStr.c_str();

    
// memory cleanup
    
delete [] data;

    
return 0;
}

The code required some modification as the name name of the key and value has since changed (FlashPlayerPlugin was previously FlashPlayer, Version was previous CurrentVersion).