How do I put new entries in the registry?

This code puts a new string entry in the registry, under HKEY_CURRENT_USER. It is designed to make the registry look like an INI file, with sections and entries. As always, parameter checking is omitted.

static REGSAM PrimarySecAccMask = KEY_QUERY_VALUE |
                                  KEY_SET_VALUE |
                                  KEY_CREATE_SUB_KEY |
                                  KEY_ENUMERATE_SUB_KEYS |
                                  KEY_NOTIFY ;

LONG WINAPI MyRegSetString (const char * szSection, 
                            const char * szEntry,
                            const char * szValue)
{ 
   char szTreeBranch [120] ;
   HKEY hMasterKey = 0 ;
   DWORD dwDisposition = 0 ;

   HKEY hTopKey = 0 ;
   LONG lReturn = 0 ;

   // Select the appropriate tree.

   strcpy (szTreeBranch, "Software\\MyCompany\\MyProgram\\");
   strcat (szTreeBranch, szSection) ;
   hTopKey = HKEY_CURRENT_USER ;

   lReturn = RegCreateKeyEx (hTopKey,
                             szTreeBranch,
                             0,
                             szMY_CLASS,
                             REG_OPTION_NON_VOLATILE,
                             PrimarySecAccMask,
                             NULL,
                             &hMasterKey,
                             &dwDisposition);
   if (lReturn == ERROR_SUCCESS)
   {
      // section exists : set the value.
      lReturn = RegSetValueEx (hMasterKey,
                               szEntry,
                               0,
                               REG_SZ,
                               (CONST BYTE *) szValue,
                               strlen
                               (szValue)+1);
   }
   else
   {
      < do some debug >
   }
   if (hMasterKey)
   RegCloseKey (hMasterKey);
   return lReturn ;
}
Download