Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 326
Hidden Avatar asked Jun 05 '13 11:06

Hidden


1 Answers

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.
like image 162
David Heffernan Avatar answered Oct 18 '22 06:10

David Heffernan