• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 185
  • Last Modified:

Accessing the windows registry.

How can I delete a key (directory) from the windows registry? I mean, not a value, but a whole key. Please give the code and an example, if possible.

Thanks in advance.

0
fcogilgo
Asked:
fcogilgo
  • 3
1 Solution
 
nietodCommented:
RegDeleteKey().

There's not much to it.  You specify a handle to a parent key in the first parameter, and a strign that specifies the sub-key (of this parent key) that is to be deleted.

continues
0
 
nietodCommented:
In windows NT the function will delete a key only if it does not have children.  The following example from the VC help shows how to write a recusive function that will delete a key with children   (I.e. it recusively deletes the children before deleting the parent.)
0
 
nietodCommented:
  // The sample code makes no attempt to check or recover from partial
   // deletions.
   //
   // A registry key that is opened by an application can be deleted
   // without error by another application in both Windows 95 and
   // Windows NT. This is by design.

   DWORD RegDeleteKeyNT(HKEY hStartKey , LPTSTR pKeyName )
   {
      DWORD   dwRtn, dwSubKeyLength;
      LPTSTR  pSubKey = NULL;
      TCHAR   szSubKey[MAX_KEY_LENGTH]; // (256) this should be dynamic.
      HKEY    hKey;

      // Do not allow NULL or empty key name
      if ( pKeyName &&  lstrlen(pKeyName))
      {
         if( (dwRtn=RegOpenKeyEx(hStartKey,pKeyName,
            0, KEY_ENUMERATE_SUB_KEYS | DELETE, &hKey )) == ERROR_SUCCESS)
         {
            while (dwRtn == ERROR_SUCCESS )
            {
               dwSubKeyLength = MAX_KEY_LENGTH;
               dwRtn=RegEnumKeyEx(
                              hKey,
                              0,       // always index zero
                              szSubKey,
                              &dwSubKeyLength,
                              NULL,
                              NULL,
                              NULL,
                              NULL
                            );

               if(dwRtn == ERROR_NO_MORE_ITEMS)
               {
                  dwRtn = RegDeleteKey(hStartKey, pKeyName);
                  break;
               }
               else if(dwRtn == ERROR_SUCCESS)
                  dwRtn=RegDeleteKeyNT(hKey, szSubKey);
            }
            RegCloseKey(hKey);
            // Do not save return code because error
            // has already occurred
         }
      }
      else
         dwRtn = ERROR_BADKEY;

      return dwRtn;
   }

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now