Thursday, May 08, 2014

Using RegOpenKeyEx and RegQueryValueEx

just putting this mess of code here for later cleanup, maybe somebody else finds it useful

assuming you need a REG_DWORD, if you need another type, REG_SZ for example, you will need to tweak this slightly.

if you have used this:

 int result;
HKEY hkey = HKEY_LOCAL_MACHINE;
HKEY hkey_fromRegOpenKey ;

result = RegOpenKeyEx(hkey, TEXT("my\\fav\\subkey\\location"), 0, KEY_READ, &hkey_fromRegOpenKey);
if(result != ERROR_SUCCESS)
{
             printf("FAIL\n");
}

  DWORD dwType;
  wchar_t szVersion[32];
  DWORD dwDataSize=sizeof(szVersion);
  memset(szVersion,'\0',32);  //TODO: wide char memset

result = RegQueryValueEx(hkey_fromRegOpenKey, "myval", NULL, &dwType, (LPBYTE)&szVersion, &dwDataSize);

You can use this to print it in C (TODO: simplify the dwValue casting mess from cpluscplus):
//extract a dword from a binary buffer
DWORD dwValue = 0;
dwValue = *((DWORD* )&szVersion); //C cast for brevity as suggested at: http://www.cplusplus.com/forum/windows/109826/
//dword is an unsigned int
printf("%u is dwValue\n", dwValue);

just putting this here so i don't lose it.

Had some issues in a different visual studio project, i think it is related to default project settings. here is a C version that handles the issue:

//
//  PrintKey takes the key, subkey and value as input and prints the value as output
//  it opens the registry, reports the value, and closes the registry when complete
//  Example usage:
// PrintKey(HKEY_LOCAL_MACHINE, "Software\\Intel\\IGFX\\USC", "CSSIMD8CompileForce");
//

void PrintKey(HKEY hkey, LPCTSTR subkey, LPCTSTR valuename )
{
long result;
HKEY hkey_fromRegOpenKey;
DWORD dwType;
wchar_t szVersion[32];
DWORD dwDataSize=sizeof(szVersion);

//it is like a database, you have to first open the registry values you want to query
result = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &hkey_fromRegOpenKey);
if(result != ERROR_SUCCESS)
{
printf("RegOpenKeyEx failed for %ls\n", subkey);

//std::cout << "RegOpenKeyEx Failed for " << subkey << std::endl ;
}

//next, query for the specific value
wmemset(szVersion,'\0',32);
result = RegQueryValueEx(hkey_fromRegOpenKey, valuename, NULL, &dwType, (LPBYTE)&szVersion, &dwDataSize);
if(result == ERROR_SUCCESS)
{
printf("%ls\t", valuename);
wprintf(L"%d\n", *szVersion);

// OLD VERSION
/*if(result == ERROR_SUCCESS)
{
std::cout << valuename << ":\t"  << *szVersion << std::endl;
}
*/
}
else
{
printf("Error reading %ls does it exist in the registry?\n", valuename);

//std::cout << "Error reading " << valuename << "does it exist in registry?" << std::endl;
}

//finally, close the registry
RegCloseKey(hkey_fromRegOpenKey);

}