How to read a registry value using TRegistry in Delphi?

202 Views Asked by At

I'm trying to read registry values in Windows using the TRegistry class.

Someone sent me an example of how it can be used, but the code isn't working.

uses Windows, Registry;

...

procedure TForm1.Button1Click(Sender: TObject);
var
  Registry: TRegistry;
  ProductName: string;
begin
  Registry := TRegistry.Create(KEY_READ); // or KEY_WRITE if you want to modify the value
  try
    Registry.RootKey := HKEY_LOCAL_MACHINE;
    ProductName := Registry.GetValue('SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName', '');
    ShowMessage('The product name is: ' + ProductName);
  finally
    Registry.Free;
  end;
end;

It's not finding GetValue. So perhaps this is not how TRegistry works or perhaps the way it works has changed in newer versions of Delphi. I am not sure and the Embarcadero docwiki is down, so I can't check there either.

How does TRegistry work? How can I use it to read values from the registry?

3

There are 3 best solutions below

1
On BEST ANSWER

There is no GetValue method on TRegistry, so the code they have sent you is wrong, or they use a helper class that they have not provided. One way would be to do this:

procedure TForm1.Button1Click(Sender: TObject);
var
  Registry: TRegistry;
  ProductName: string;
begin
  Registry := TRegistry.Create(KEY_READ); // or KEY_WRITE if you want to modify the value
  try
    Registry.RootKey := HKEY_LOCAL_MACHINE;
    ProductName := '';
    if Registry.OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion', False) then
    try
      ProductName := Registry.ReadString('ProductName');
    finally
      Registry.CloseKey;
    end;
    ShowMessage('The product name is: ' + ProductName);
  finally
    Registry.Free;
  end;
end;
2
On

Here you have an example:

procedure TForm1.Button1Click(Sender: TObject);
var
   reg: TRegistry;
begin
   reg:= TRegistry.Create(KEY_READ);
   reg.RootKey:=  HKEY_LOCAL_MACHINE;
   reg.OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion', false);
   ShowMessage(reg.ReadString('ProductName'));
   reg.Free;
end;
1
On

The Embarcadero Doku on TRegistry is available:

Using TRegistry