Add controls to a form at runtime and stream the result to a file (Views: 29)
Problem/Question/Abstract: Is it possible to add controls to a form at runtime, then stream the result to single file, thus preserving all changes for next application run? Answer: Yes, with some caveats. You need to register all control classes that are used on the form plus all that the user may add at runtime. Here is a little example: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} const formdata = 'formdata.bin'; procedure TForm1.Button1Click(Sender: TObject); begin with TEdit.Create(self) do begin left := button1.Left + button1.width + 10; top := button1.top; Name := 'NewEdit'; parent := self; end; end; procedure TForm1.Button2Click(Sender: TObject); var fs: TFileStream; begin fs := TFileStream.Create(ExtractFilePath(ParamStr(0)) + formdata, fmCreate); try fs.WriteComponent(self); finally fs.free end; end; procedure TForm1.FormCreate(Sender: TObject); var filename: string; fs: TFileStream; i: integer; begin filename := ExtractFilePath(ParamStr(0)) + formdata; if fileExists(filename) then begin for i := ComponentCount - 1 downto 0 do Components[i].Free; fs := Tfilestream.create(filename, fmOpenRead or fmShareDenyWrite); try fs.ReadComponent(self); button1.enabled := false; finally fs.free end; end; end; initialization RegisterClasses([TButton, TEdit]); end. |