Search code examples
delphiregistrydword

Write dword value in Registry with Delphi


My program has a TWebBrowser where the user can open all kinds of local documents. To avoid that for example a Word document is opened in Word instead of in the TWebBrowser (that is to say, in Internet Explorer), I successfully use a fix in the Registry, by executing a .reg file with this instruction:

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Word.Document.12] "BrowserFlags"=dword:80000024

I am trying to introduce that instruction in the Delphi program itself, with this code:

procedure RegOpenExplorer;
var
  reg: TRegistry;
begin
  reg:= TRegistry.Create;
  try
    reg.RootKey:=HKEY_LOCAL_MACHINE;
    reg.OpenKey('SOFTWARE\Classes\Word.Document.12\', true);
    reg.WriteInteger('BrowserFlags',80000024);
    reg.CloseKey;
  finally
    reg.Free;
  end;
end;

It does not work, actually the effect is undoing the fix.

When successfully manipulated with the .reg file (or manually), the Registry key looks like this:

good key

But with my unsuccessful Delphi Code, the key becomes as follows:

bad key

The difference is the number in brackets, but that is something that the Registry introduces automatically by itself.


Solution

  • The numeric value in the .reg file is encoded as hex. Since you are passing an integer literal to WriteInteger(), you need to prefix it with a $ to make the compiler interpret it as hex:

    reg.WriteInteger('BrowserFlags', $80000024);
    

    That being said, note that you are writing to HKEY_LOCAL_MACHINE, and more importantly you are opening the key with KEY_ALL_ACCESS access rights (the default access rights that TRegistry uses). This is going to require you to run your app elevated as an administrator, if it is not already. You should be setting the TRegistry.Access property to KEY_SET_VALUE instead, and maybe even writing to HKEY_CURRENT_USER instead.

    procedure RegOpenExplorer;
    var
      reg: TRegistry;
    begin
      reg := TRegistry.Create(KEY_SET_VALUE);
      try
        reg.RootKey := HKEY_LOCAL_MACHINE; // or HKEY_CURRENT_USER
        if reg.OpenKey('SOFTWARE\Classes\Word.Document.12\', true) then
        try
          reg.WriteInteger('BrowserFlags', $80000024);
        finally
          reg.CloseKey;
        end;
      finally
        reg.Free;
      end;
    end;