Hidden
Hidden

Reputation: 3628

How to check if a registry key exists

I don't know wheres my mistake. It always jumps to the else branch, but the key exist, I checked it several times.

var
  reg : TRegistry;
begin
    with TRegistry.Create do try
      RootKey:=HKEY_CURRENT_USER;
      OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run', False);
    if KeyExists('nginx.exe') then begin
      ShowMessage('Ja geht ist da');
      Result := True;
      btnAutostart.ImageIndex := 5
    end
    else begin
      Result := False;
      btnAutostart.ImageIndex := 0;
    end;
    finally
      Free;
    end;
end;

Upvotes: 6

Views: 10388

Answers (1)

David Heffernan
David Heffernan

Reputation: 612914

You need to call ValueExists rather than KeyExists. A key is what appears as a folder in Regedit but you are looking for a value named nginx.exe in the key HKCU\Software\...\Run.

Some other comments:

  1. Since you are only reading from the registry, use OpenKeyReadOnly rather than OpenKey.
  2. Check the return value of OpenKeyReadOnly in case the key cannot be opened.
  3. If you actually need to do this with HKLM (as you state in a comment), watch out for registry redirection confusion when running 32 bit process on 64 bit system.

Upvotes: 13

Related Questions