views:

730

answers:

3

Hi There, Im trying to code a Visual C++ 2005 routine that checks the registry for certain keys/values. I have no trouble in writing code using c# but I need it in C++. Anybody know how to do this using c++ in vs2005.

Many thanks Tony

+4  A: 

There are Win32 APIs available: take a look at MSDN for RegOpenKey and friends (and the Registry Functions in general).

Here is an example of 'Deleting a Key with Subkeys'.

dirkgently
+4  A: 

Here is some pseudo-code to retrieve the following:

  1. If a registry key exists
  2. What the default value is for that registry key
  3. What a string value is
  4. What a DWORD value is

Example code:

Include the library dependency: Advapi32.lib

Put the following in your main or where you want to read the values:

HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lres == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");


Put these wrapper functions at the top of your code:

LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
 nValue = nDefaultValue;
 DWORD dwBufferSize(sizeof(DWORD));
 DWORD nResult(0);
 LONG nError = ::RegQueryValueExW(hKey,
  strValueName.c_str(),
  0,
  NULL,
  reinterpret_cast<LPBYTE>(&nResult),
  &dwBufferSize);
 if (ERROR_SUCCESS == nError)
 {
  nValue = nResult;
 }
 return nError;
}


LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
 DWORD nDefValue((bDefaultValue) ? 1 : 0);
 DWORD nResult(nDefValue);
 LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
 if (ERROR_SUCCESS == nError)
 {
  bValue = (nResult != 0) ? true : false;
 }
 return nError;
}


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;
}
Brian R. Bondy
A: 

Yuh. Added this code, MS Visual Studio 2008 SP1, C++ project, I get null

bExistsAndSuccess: 1 bDoesNotExistsSpecifically: 0 strValueOfBinDir: (null)

Key is correct, a false key I get:

bExistsAndSuccess: 0 bDoesNotExistsSpecifically: 1 strValueOfBinDir: (null)

Something not returning the string correctly. Using fwprintf to print to a temporary file.

EDIT: Epic fail. I wasn't using .c_str() on output

Homerbrain