2004. április 2., péntek

Create a form that saves its component state automatically


Problem/Question/Abstract:

I would like to know how to save a forms appearance once it has been changed by a user.

Answer:

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Memo1: TMemo;
    CheckBox1: TCheckBox;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    RadioGroup1: TRadioGroup;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  private
    function FormFilename: string;
  public
    constructor Create(aOwner: TComponent); override;
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
  close
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
  fs: TFilestream;
begin
  fs := TFilestream.Create(FormFilename, fmCreate);
  try
    fs.WriteComponent(self);
  finally
    fs.free;
  end;
end;

function TForm1.FormFilename: string;
begin
  Result := ExtractFilePath(ParamStr(0)) + Classname + '.DAT';
end;

constructor TForm1.Create(aOwner: TComponent);
var
  fs: TFileStream;
  fname: string;
begin
  fname := FormFilename;
  if FileExists(fname) then
  begin
    CreateNew(aOwner);
    fs := TFileStream.Create(fname, fmOpenread or fmShareDenyWrite);
    try
      fs.ReadComponent(self);
    finally
      fs.free;
    end;
  end
  else
    inherited Create(aOwner);
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése