Registry manipulation class with exception handling

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This is another registry class manipulation which uses exception handling.

It basically uses the extended API provided for registry access (RegXXXXXEx) and I tried to simplify it as possible. Although right now there’s no function overidables for Read/Write to much simplify the passing of data (so you don’t have to typecast them to LPBYTE) but I’ll work out this one.

Opening of data is fairly simple, you just specify the location of the key handle (HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER…etc) and the subkey (SOFTWARE\MyCompany\MyProject…). The option (reserved for future enhancement of the API) and the security access mask (default to all access) are optional. You can open the registry via call to CRegistry::Open() or just by passing the parameters of the Open() function to the constructor.

CRegistry reg1( HKEY_LOCAL_MACHINE, “SOFTWARE\MyCompany\somedata” );


CRegistry reg2;
reg2.Open( HKEY_LOCAL_MACHINE, “SOFTWARE\MyCompany\someotherdata” );

Reading and writing values are done by calls to Read() and Write() respectively.

Since it is using the CException derived class to handle exception, it is also easier to display the error encountered:


try {
CRegistry regConfig;
regConfig.Open( HKEY_LOCAL_MACHINE, “SOFTWARE\MyCompany\MyData” );
DWORD nLen;
BYTE nSomeByteData;
char szSomeStringData;
DWORD nSomeDWordData;
/*if you dont want the type of the data to be returned…
then specify NULL on the third parameter…
*/
regConfig.Read( &nSomeData, ( nLen=sizeof( nSomeData ), &nLen ), NULL, “Some Byte Data” );
regConfig.Read(( LPBYTE )&szSomeStringData, ( nLen=sizeof( szSomeStringData ), &nLen ), NULL, “Some String Data” );
regConfig.Read(( LPBYTE )&nSomeDWordData, ( nLen=sizeof( nSomeDWordData ), &nLen ), NULL, “Some DWord Data” );

/* … but if you want the data type, then pass a DWORD pointer
*/
DWORD nType;
char nSomeUnknownData[ 50 ];
regConfig.Read(( LPBYTE )&nSomeUnknownData, ( nLen=sizeof( nSomeUnknownData ), &nLen ), &nType, “Some Unknown Data” );
/* your nType now may have the following value: REG_BINARY, REG_DWORD, REG_SZ….
*/
}

catch( CRegistryException *regError ) {
// display the error
regError->ReportError();

// now delete the handle
regError->Delete();
}

All the data and data types used by this class are also the same one being used by the API (like HKEY_LOCAL_MACHINE, KEY_READ, REG_EXPAND_SZ, REG_LINK….etc).

Download source – 3 KB

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read