Click to See Complete Forum and Search --> : Windows SDK Registry: How can I read data from the registry?


Andreas Masur
May 23rd, 2003, 03:55 PM
Q: How can I read data from the registry?

A:


HKEY hKey;
DWORD dwSize = 0;
DWORD dwDataType = 0;
DWORD dwValue = 0;

if(::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
"System\\CurrentControlSet\\Control\\Windows",
0,
KEY_QUERY_VALUE,
&hKey) == ERROR_SUCCESS)
{
// Get CSD version
dwSize = sizeof(dwValue);

if(::RegQueryValueEx(hKey,
"CSDVersion",
0,
&dwDataType,
reinterpret_cast<BYTE *>(&dwValue),
&dwSize) != ERROR_SUCCESS)
{
// Close key
::RegCloseKey(hKey);

// Error handling
}
else
{
// Work with value
// Close key
::RegCloseKey(hKey);
}
}
else
// Error handling;

<br>

ovidiucucu
June 25th, 2005, 10:56 AM
Q: The RegQueryValueEx function returns an error code 234 (ERROR_MORE_DATA) that means "more data is available". How many bytes must be allocated for value buffer to assure this error does not appear anymore?

A: To find the necessary buffer size, call 'RegQueryValueEx()' with a 'NULL' value in 'lpData' parameter. After return, the variable pointed by 'lpcbData' will contain the size of the data. Allocate the buffer 'lpData' then call 'RegQueryValueEx()' again:


HKEY hKey = NULL;
DWORD dwSize = 0;
DWORD dwDataType = 0;
LPBYTE lpValue = NULL;
LPCTSTR const lpValueName = _T("Directory");

LONG lRet = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
_T("System\\CurrentControlSet\\Control\\Windows"),
0,
KEY_QUERY_VALUE,
&hKey);
if(ERROR_SUCCESS != lRet)
{
// Error handling (see this FAQ (http://www.codeguru.com/forum/showthread.php?t=318721))
return;
}
// Call once RegQueryValueEx to retrieve the necessary buffer size
::RegQueryValueEx(hKey,
lpValueName,
0,
&dwDataType,
lpValue, // NULL
&dwSize); // will contain the data size

// Alloc the buffer
lpValue = (LPBYTE)malloc(dwSize);

// Call twice RegQueryValueEx to get the value
lRet = ::RegQueryValueEx(hKey,
lpValueName,
0,
&dwDataType,
lpValue,
&dwSize);
::RegCloseKey(hKey);
if(ERROR_SUCCESS != lRet)
{
// Error handling
return;
}
// Enjoy of lpValue...
// free the buffer when no more necessary
free(lpValue);

<br>