Working with the Registry in VC++

Working correctly with the Windows Registry might prove a little difficult, especially for beginners. One thing one should care about for example is using the correct access rights (not just the default ones) when creating a registry key. To ease the burden of directly using the Win32 registry API, I decided to wrap them inside two classes and make them available for anyone that wants to use them.

The classes that I put together are:

  • SecurityAttributesUtils: this is transparent for the developer, and is used to create the necessary access rights for creating a registry key;
  • RegistryUtils: offers static functions for creating, deleting and closing a key, as well as reading and writing double words, strings and binary data to/from the registry;
  • RegistryUtilsEx: a class based on RegistryUtils used for reading and writing strings and binary data, that uses STL’s std::string or std::wstring classes.

To create a key you should use RegistryUtils::CreateKey. It takes a handle to an open key (usually one of the predefined keys HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, etc. or an already opened key), the name of the subkey the function opens or creates and the desire access rights. It returns the handle to the opened or created key as the first argument, and a value indicating the success or failure.

HKEY hKey = NULL; 
// create or open the key 
RegistryUtils::RegResult OpenMode = RegistryUtils::CreateKey(HKEY_CURRENT_USER, 

To write a string use either RegistryUtils::WriteString or RegistryUtilsEx::WriteString string if you use STL std::string or std::wstring. It takes the handle to the key, the name of the value and the value to write.

RegistryUtilsEx::WriteString(hKey, _T("key1"), _T("value1"));

To read a string use either RegistryUtils::ReadString or RegistryUtilsEx::ReaderString, the later for working with STL’s strings.

tstring str; 
// read a string 
if(RegistryUtils::Success != RegistryUtilsEx::ReadString(hKey, _T("key1"), str)) 
  // if not present, write it in registry 
  RegistryUtilsEx::WriteString(hKey, _T("key1"), _T("value1")); 

  // now it should be read 
  RegistryUtilsEx::ReadString(hKey, _T("key1"), str); 

Simillary, you can use ReadDword() and WriteDword() for reading and writing integer values, and ReadBinary() and WriteBinary() for generic binary data.

// read an integer 
DWORD number; 
if(RegistryUtils::Success != RegistryUtils::ReadDword(hKey, _T("key2"), number)) 
  // if not present in the registry, write it 
  RegistryUtils::WriteDword(hKey, _T("key2"), 44); 

  // this time it should be read 
  RegistryUtils::ReadDword(hKey, _T("key2"), number); 

To close an opened key call RegistryUtils::CloseKey().


Additionally, RegistryUtils::DeleteKey() can be used to delete a specified key, along with all its sub-keys and values.

The code is available for download here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.