MFC reading and writing from the registry

After spending some time today coding in MFC I realized I had to store some values in the registry. I haven't done this in a while and didn't find much help on the net so I am adding my experience to hopefully help some folks out. It used to be you had to use the Get/Write private profile string methods in the Win32 API. MFC has made that easier with the CSettingsStore class. This is a new class in the MFC feature pack. So to use it you have to have service pack 1 installed for visual studio 2008.

To use the class all you have to do is create an instance of that class and you can use it's methods to read,write,create, and pretty much do whatever you want in the registry. So let's look at some code that does some stuff in the registry.

We're going to create/open a new key and write some values to it
// let's create a new pointer to our registry class 
// Sadly the MSDN MFC documentation seems to be wrong
// on the constructor logic.
// This will put us under the HKEY_CURRENT_USER node
// with full read/write rights.
CSettingsStore* m_pRegistry = new CSettingsStore( FALSE, FALSE );

int test = 100;
bool testBool = false;

// First always check your pointer to make sure nothing
// jinky has happened to it.
// CreateKey opens the key or if it doesn't exist
// creates a new key and sets it as the default current node.
if( m_pRegistry &&
m_pRegistry->CreateKey( _T("\\Software\\Test Application") ) )
{
// all the methods on the CSettingsClass return BOOL to
// let you know if they succeeded
// now we're under the node we want so we're going
// to write some values, the Write methods looks for DWORD
// so we need to do some casting to ensure our values get
// written correctly
m_pRegistry->Write( _T("intValue"), (int)test );
m_pRegistry->Write( _T("boolValue"), (bool)testBool );

// always close our current connection when done
m_pRegistry->Close();

}


Reading is much the same. We create an instace of the CSettingsClass object and call the Read method.

// let's create a new pointer to our registry class 
// Sadly the MSDN MFC documentation seems to be wrong
// on the constructor logic.
// This will put us under the HKEY_CURRENT_USER node
// with full read/write rights.
CSettingsStore* m_pRegistry = new CSettingsStore( FALSE, FALSE );

int test = ;

// First always check your pointer to make sure nothing
// jinky has happened to it.
// CreateKey opens the key or if it doesn't exist
// creates a new key and sets it as the default current node.
if( m_pRegistry &&
m_pRegistry->CreateKey( _T("\\Software\\Test Application") ) )
{
// read in the value from the node
// again this will bring back a bool result for success or failure
m_pRegistry->Read( _T("test"), (int)test );

// always close our current connection when done
m_pRegistry->Close();

}


So there is some basic usage on how to read/write to the registry. A very easy way to quickly get data in and out for your application.

Comments

Popular Posts