Search code examples
c++windowsregistrykey

C++ Search Windows Registry


I'm trying to search the registry for keys in a particular group(Local-> Windows -> Uninstall) so I can eventually uninstall these applications programatically. I am having problems getting the key name so I can open it. Here is what I have tried:

void Uninstall::uninstallProgram(string appName)
{
    HKEY currentKey;
    TCHAR name[1024];
    DWORD dwSize = 1024, dwIdx = 0;
    FILETIME fTime;
    long result;

    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, POLICY_KEY, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &currentKey);

    if (result != ERROR_SUCCESS)
    {
        cout << "Error opening Installation Registry, verify that this location exists under: " << POLICY_KEY << endl;
        cin.get();
    }
    else
    {
        /*
         * The installation path has been verified, now need to start looking for the correct program to uninstall
         */

        for(int index = 0; result == ERROR_SUCCESS; index++)
        {
            if (RegEnumKeyEx(currentKey, 0, name, &dwSize, NULL, NULL, NULL, &fTime))
            {
                cout << string() << name << endl;
//              if (name == appName)
//              {
//                  system(execute the uninstall string)
//              }
            }
        }


    }

How can I retrieve the current key name to compare it against the name of the application that I am trying to uninstall? Thanks.


Solution

  • It seems that you just forgot to request KEY_ENUMERATE_SUB_KEYS access right. Also it's possible that I do not understand exactly what are you trying to do but AFAIK Uninstall folder have different location.

    HKEY currentKey;
    TCHAR name[1024];
    DWORD dwSize = 1024, dwIdx = 0;
    long result;
    result = RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" ), 0, KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE | KEY_SET_VALUE, &currentKey);
    
    if (result != ERROR_SUCCESS)
    {
      // fail
    }
    else
    {
      DWORD index = 0;
      while ( ERROR_SUCCESS == RegEnumKeyEx(currentKey, index, name, &dwSize, NULL, NULL, NULL, NULL) ) {
        // name buffer is already contains key name here
        // ...
        dwSize = 1024; // restore dwSize after is is set to key's length by RegEnumKeyEx
        ++index; // increment subkey index
      } 
    }