unit RegExampleDelphi;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Registry, StdCtrls;

type
  TForm3 = class(TForm)
    InsertToRegBtn: TButton;
    DeleteFromRegBtn: TButton;
    procedure InsertToRegBtnClick(Sender: TObject);
    procedure DeleteFromRegBtnClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

// BeginExample: TRegistry
// Class: Registry.TRegistry
// Method: Registry.TRegistry.Create
// Method: Registry.TRegistry.KeyExists
// Method: Registry.TRegistry.OpenKey
// Method: Registry.TRegistry.WriteDateTime
// Method: Registry.TRegistry.WriteString
// Method: Registry.TRegistry.WriteExpandString
// Method: Registry.TRegistry.CloseKey
// Method: Registry.TRegistry.DeleteKey
// Property: Registry.TRegistry.RootKey
// Property: Registry.TRegistry.Access

// BeginCode
{
This example shows how to use the TRegistry class in order to
find, insert and delete Keys and Items into the Windows Registry.
This example uses two buttons: InsertToRegBtn and DeleteFromRegBtn,
on a form, for inserting and deleting the values.
}
procedure TForm3.InsertToRegBtnClick(Sender: TObject);
var
  reg        : TRegistry;
  openResult : Boolean;
  today      : TDateTime;
begin
  reg := TRegistry.Create(KEY_READ);
  reg.RootKey := HKEY_LOCAL_MACHINE;

  if (not reg.KeyExists('Software\\MyCompanyName\\MyApplication\\')) then
    begin
      MessageDlg('Key not found! Created now.',
					        mtInformation, mbOKCancel, 0);
    end;
  reg.Access := KEY_WRITE;
  openResult := reg.OpenKey('Software\\MyCompanyName\\MyApplication\\',True);

  if not openResult = True then
    begin
      MessageDlg('Unable to create key! Exiting.',
                  mtError, mbOKCancel, 0);
      Exit();
    end;

  {checking if the values exist and inserting when neccesary}

  if not reg.KeyExists('Creation\ Date') then
    begin
      today := Now;
  		reg.WriteDateTime('Creation\ Date', today);
    end;

  if not reg.KeyExists('Licenced\ To') then
    begin
  		reg.WriteString('Licenced\ To', 'MySurname\ MyFirstName');
    end;

  if not reg.KeyExists('App\ Location') then
    begin
  		reg.WriteExpandString('App\ Location',
                            '%PROGRAMFILES%\\MyCompanyName\\MyApplication\\');
    end;

  if not reg.KeyExists('Projects\ Location') then
    begin
  		reg.WriteExpandString('Projects\ Location',
                            '%USERPROFILE%\\MyApplication\\Projects\\');
    end;

  reg.CloseKey();

end;

procedure TForm3.DeleteFromRegBtnClick(Sender: TObject);
var
  reg : TRegistry;
begin
  reg := TRegistry.Create(KEY_WRITE);
  reg.RootKey := HKEY_LOCAL_MACHINE;

  reg.DeleteKey('Software\\MyCompanyName\\MyApplication');
  reg.DeleteKey('Software\\MyCompanyName');

  reg.CloseKey();
end;
// EndCode
// EndExample: TRegistry
end.
