Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to read registry key value to std::string?

Tags:

c++

registry

What's the simplest way to read a registry key value to std::String?

Say I've got :

HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value1 = "some text"
HKEY_LOCAL_MACHINE / SOFTWARE / MyApp / value2 = "some more text"

How do I get those values to std::string in a fast way ?

like image 671
Maciek Avatar asked Nov 28 '09 20:11

Maciek


People also ask

How to read value from registry key?

Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.

What does Reg_sz mean?

REG_SZ. A null-terminated string. This will be either a Unicode or an ANSI string, depending on whether you use the Unicode or ANSI functions.

What is Hkey?

The HKEY_LOCAL_MACHINE, otherwise known as HKLM, is a Windows Registry tree that contains configuration data that is used by all users in Windows. This includes information about Windows services, drivers, programs that automatically run for every user, and general OS settings.


1 Answers

I have some very old code, but it should give you a good idea:

/**
* @param location The location of the registry key. For example "Software\\Bethesda Softworks\\Morrowind"
* @param name the name of the registry key, for example "Installed Path"
* @return the value of the key or an empty string if an error occured.
*/
std::string getRegKey(const std::string& location, const std::string& name){
    HKEY key;
    TCHAR value[1024]; 
    DWORD bufLen = 1024*sizeof(TCHAR);
    long ret;
    ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, location.c_str(), 0, KEY_QUERY_VALUE, &key);
    if( ret != ERROR_SUCCESS ){
        return std::string();
    }
    ret = RegQueryValueExA(key, name.c_str(), 0, 0, (LPBYTE) value, &bufLen);
    RegCloseKey(key);
    if ( (ret != ERROR_SUCCESS) || (bufLen > 1024*sizeof(TCHAR)) ){
        return std::string();
    }
    std::string stringValue = std::string(value, (size_t)bufLen - 1);
    size_t i = stringValue.length();
    while( i > 0 && stringValue[i-1] == '\0' ){
        --i;
    }
    return stringValue.substr(0,i); 
}
like image 125
Yacoby Avatar answered Oct 10 '22 09:10

Yacoby