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.

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.

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

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

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.