Monday 31 August 2009

Reading and Writing from Windows Registry

The following is an example of reading and writing from Windows Registry using C++. The code have been created based on examples from MSDN. I have provided the MSDN references in the code in case you want to lookup the documentation.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of reading and writing from registry
#include <windows.h>
#include <iostream>

using namespace
std;

#define WIN_32_LEAN_AND_MEAN

void
writeToRegistry(void)
{

DWORD lRv;
HKEY hKey;

//Check if the registry exists
//http://msdn.microsoft.com/en-us/library/ms724897(VS.85).aspx
lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_WRITE,
&
hKey
);


if
(lRv != ERROR_SUCCESS)
{

DWORD dwDisposition;

// Create a key if it did not exist
//http://msdn.microsoft.com/en-us/library/ms724844(VS.85).aspx
lRv = RegCreateKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
, //"Use Multi-Byte Character Set" by using L
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&
hKey,
&
dwDisposition
);


DWORD dwValue = 1;

//http://msdn.microsoft.com/en-us/library/ms724923(VS.85).aspx
RegSetValueEx(
hKey,
L"Something"
,
0
,
REG_DWORD,
reinterpret_cast
<BYTE *>(&dwValue),
sizeof
(dwValue)
);


//http://msdn.microsoft.com/en-us/library/ms724837(VS.85).aspx
RegCloseKey(hKey);
}
}


void
readValueFromRegistry(void)
{

//Example from http://msdn.microsoft.com/en-us/library/ms724911(VS.85).aspx

HKEY hKey;

//Check if the registry exists
DWORD lRv = RegOpenKeyEx(
HKEY_CURRENT_USER,
L"Software\\Zahid"
,
0
,
KEY_READ,
&
hKey
);


if
(lRv == ERROR_SUCCESS)
{

DWORD BufferSize = sizeof(DWORD);
DWORD dwRet;
DWORD cbData;
DWORD cbVal = 0;

dwRet = RegQueryValueEx(
hKey,
L"Something"
,
NULL,
NULL,
(
LPBYTE)&cbVal,
&
cbData
);


if
( dwRet == ERROR_SUCCESS )
cout<<"\nValue of Something is " << cbVal << endl;
else
cout<<"\nRegQueryValueEx failed " << dwRet << endl;
}

else

{

cout<<"RegOpenKeyEx failed " << lRv << endl;
}
}


int
main()
{

writeToRegistry();
readValueFromRegistry();
return
0;
}


The output is as follows:

3 comments:

  1. I'm new in C++
    now I making .xll for excel using XLW - A C++ wrapper for the Excel C API (http://nchc.dl.sourceforge.net/project/xlw/xlw/xlw%205.0/xlw-5.0.0a7.exe)
    How do I read and write to windows registry?

    ReplyDelete
    Replies
    1. You will have to ask someone in their forum. I am not sure what it does or what it can do.

      Delete
  2. After all an example that works! Congratulations! Thank you very much!

    ReplyDelete