Brian
Brian

Reputation: 339

Delphi adding to registry failed

I am trying to add values to Internet Explorer's Registry key from an addon. My understanding is if OpenKey() doesn't find the Registry key, then it creates the key because of the true parameter I am using. But it's not being created, and the function returns false. Any idea what I'm doing wrong?

procedure DoInitialization;
var
  ...
  reg1: TRegistry;
begin
  reg1 := tRegistry.Create(KEY_ALL_ACCESS);
  try 
    if reg1.OpenKey('HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\Low Rights\ElevationPolicy\{B93642D4-0A6D-11DF-AD36-FF4756D89593}', true) then begin    
      reg1.WriteString('AppPath', ClientDir);
      reg1.WriteInteger('Policy', $00000003);
      reg1.WriteString('AppName', 'xxxxxxxx.exe');
    end else
      ShowMessage('False');
  finally
    reg1.CloseKey;
  end;
  ...
end;

Upvotes: -1

Views: 1265

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598299

DON'T use KEY_ALL_ACCESS, that requires admin rights to use. In this situation, you are just writing values to the key, so all you need to use is KEY_SET_VALUE instead. Don't request more rights than you actually need.

Also, you need to use the RootKey property to specify HKEY_CURRENT_USER, do not include it in the key path string.

And, you are leaking the TRegistry object.

Try this instead:

procedure DoInitialization;
var
  ...
  reg1: TRegistry;
begin
  reg1 := TRegistry.Create(KEY_SET_VALUE);
  try 
    reg1.RootKey := HKEY_CURRENT_USER;
    if reg1.OpenKey('\SOFTWARE\Microsoft\Internet Explorer\Low Rights\ElevationPolicy\{B93642D4-0A6D-11DF-AD36-FF4756D89593}', true) then
    begin    
      try
        reg1.WriteString('AppPath', ClientDir);
        reg1.WriteInteger('Policy', $00000003);
        reg1.WriteString('AppName', 'xxxxxxxx.exe');
      finally
        reg1.CloseKey;
      end;
    end else
      ShowMessage('False');
  finally
    reg1.Free;
  end;
  ...
end;

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613572

The root key is to be set in the RootKey property, not the key.

reg1.RootKey := HKEY_CURRENT_USER;
if reg1.OpenKey('Software\...', True) then begin
  ....

In fact, HKEY_CURRENT_USER is the default so strictly speaking you don't need to set it. But it is, in my opinion, helpful to be explicit.

If that fails then likely you have got a mistake in the registry key string, or perhaps the user does not have sufficient rights. Use the LastError property of reg1 to find out why the call failed.

Note that you leak reg1. You need to destroy the object in the finally block.

Upvotes: 1

Related Questions