Mirror

How to save components to a file or stream (2) (Views: 26)


Problem/Question/Abstract:

I would like to stream selected components (say a panel with some other components on it) to a DFM like (text preferred over binary) file and be able to load it and restore them programatically.

Answer:

You need to save this component with root (where its handlers are declared), f.e., with TFormX:

{ ... }
type
  TForm1 = class(TForm)
    MyComponent: TMyComponent;
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  private
    { Private declarations }
  public
    constructor Create(AOwner: TComponent); override;
    function FormFileName: string;
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

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

constructor TForm1.Create(AOwner: TComponent);
var
  fname: string;
begin
  RegisterClass(TMyComponent); {And anything else that is required }
  fname := FormFilename;
  if FileExists(fname) then
  begin
    CreateNew(AOwner);
    ReadComponentResFile(fname, Self);
  end
  else
    inherited Create(AOwner);
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  WriteComponentResFile(FormFileName, Self);
  UnregisterClass(TMyComponent);
end;

<< Back to main page