Automatically loading a form on demand
Copyright © 2000 Ernesto De Spirito
![]() |
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 a little trick. Here goes the source code:
unit Unit2;
interface
uses ...;
type
TForm2 = class(TForm)
...
end;
function Form2: TForm2;
var
// Form2: TForm2;
implementation
{$R *.DFM}
var
RealForm2: TForm2;
function Form2: TForm2;
begin
if RealForm2 <> nil then
Form2 := RealForm2
else
Application.CreateForm(TForm2, Result);
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
RealForm2 := Self;
end;
procedure TForm2.FormDestroy(Sender: TObject);
begin
RealForm2 := nil;
end;
...
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. The
initial value is nil (Delphi initializes strings and
object variables).
![]() |



