Author: Ernesto De Spirito
How can I get my forms created automatically "on demand" (when they are referenced)?
Answer:
If you have programmed in Visual Basic, probably you know what we are talking
about: when you reference a property or a method of form, it is automatically
created if necessary. For example, the following code will generate an exception in
Delphi if Form2 was not previously created:
Form2.Show;
However it would work perfectly well in Visual Basic (without the semicolon, of
course), and we can make it work it Delphi too with this little trick:
1 unit Unit2;
2 3 interface4 5 uses...;
6 7 type8 TForm2 = class(TForm)
9 ...
10 end;
11 12 function Form2: TForm2;
13 14 var15 // Form2: TForm2;16 17 implementation18 19 {$R *.DFM}20 21 var22 RealForm2: TForm2;
23 24 function Form2: TForm2;
25 begin26 if RealForm2 <> nilthen27 Form2 := RealForm2
28 else29 Application.CreateForm(TForm2, Result);
30 end;
31 32 procedure TForm2.FormCreate(Sender: TObject);
33 begin34 RealForm2 := Self;
35 end;
36 37 procedure TForm2.FormDestroy(Sender: TObject);
38 begin39 RealForm2 := nil;
40 end;
41 42 initialization43 RealForm2 := nil;
44 end.
What we did was replacing the Form2 variable with a function with the same name and
type. This function uses a "hidden" variable (declared in the implementation
section) -RealForm2- to check if the form is created or not (and in the latter
case, it will create it automatically). We set the value of this hidden variable in
the OnCreate and OnDestroy events of the form to the address of the form or nil
respectively.
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php