Author: Lou Adler
Is it possible to reset the state of controls like TEdit.text, TCheckBox.Checked,
etc. at runtime to their original design-time values without assigning the property
values for each control again?
Answer:
If I understand you correctly you want all controls on the form to revert to the
design-time values when the user clicks the a cancel button, for example. The
generic way would be to reload the controls from the form resource. The main
problem is that you have to delete all components on the form first or you get a
load of errors since the component loading code really creates new instances of all
components on the form.
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 ExtCtrls,
8 StdCtrls;
9
10 const
11 UM_RELOADFORM = WM_USER + 321;
12
13 type
14 TForm1 = class(TForm)
15 Button1: TButton;
16 CheckBox1: TCheckBox;
17 CheckBox2: TCheckBox;
18 CheckBox3: TCheckBox;
19 RadioGroup1: TRadioGroup;
20 RadioGroup2: TRadioGroup;
21 CheckBox4: TCheckBox;
22 CheckBox5: TCheckBox;
23 procedure Button1Click(Sender: TObject);
24 private
25 { Private declarations }
26 procedure UMReloadForm(var msg: TMessage); message UM_RELOADFORM;
27 public
28 { Public declarations }
29 end;
30
31 var
32 Form1: TForm1;
33
34 implementation
35
36 {$R *.DFM}
37
38 procedure TForm1.Button1Click(Sender: TObject);
39 begin
40 {Delay action until button click code has finished executing}
41 PostMessage(handle, UM_RELOADFORM, 0, 0);
42 end;
43
44 procedure TForm1.UMReloadForm(var msg: TMessage);
45 var
46 i: Integer;
47 rs: TResourceStream;
48 begin
49 {Block form redrawing}
50 Perform(WM_SETREDRAW, 0, 0);
51 try
52 {Delete all components on the form}
53 for i := ComponentCount - 1 downto 0 do
54 Components[i].Free;
55 {Find the forms resource}
56 rs := TResourceStream.Create(FindClassHInstance(TForm1), Classname, RT_RCDATA);
57 try
58 {Recreate components from the form resource}
59 rs.ReadComponent(self);
60 finally
61 rs.free
62 end;
63 finally
64 {Redisplay form}
65 Perform(WM_SETREDRAW, 1, 0);
66 Invalidate;
67 end;
68 end;
69
70 end.
|