4th february

Pascal

Delphi

VCL Components

CLX Components

Glyphs, Icons, Cursors, Videos

Logos

Sample Projects

Tools

Articles, Code Examples, Tips

Links

Code Examples

How to use Registry for saving and restoring form state and position?

unit Main;

interface

uses Windows, SysUtils, ... , Registry;

type
  TMainForm = class(TForm)
  ...
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  ...
  private
    procedure ReadSettings;
    procedure WriteSettings;
  public
    FIniFile: TRegIniFile;
  end;

var
  MainForm: TMainForm;

const
  Section = 'MainWindow';

implementation

procedure TMainForm.ReadSettings;
begin
  with FIniFile do
  begin
    with MainForm do
    begin
      Left := ReadInteger(Section, 'Left', Left);
      Top := ReadInteger(Section, 'Top', Top);
      Height := ReadInteger(Section, 'Height', Height);
      Width := ReadInteger(Section, 'Width', Width);
      if ReadBool(Section, 'Maximized', False) = True then
        WindowState := wsMaximized;
    end;
  end;
end;

procedure TMainForm.WriteSettings;
begin
  with FIniFile do
  begin
    with MainForm do
    begin
      if WindowState = wsMaximized then
      begin
        WriteBool(Section, 'Maximized', True);
      end else
      begin

        WriteBool(Section, 'Maximized', False);
        WriteInteger(Section, 'Left', Left);
        WriteInteger(Section, 'Top', Top);
        WriteInteger(Section, 'Height', Height);
        WriteInteger(Section, 'Width', Width);
      end;
    end;
  end;
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  FIniFile := TRegIniFile.Create('Software\MyCompany\MySoftware\Version');
  ReadSettings;
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  WriteSettings;
  FIniFile.Free;
end;