2006. április 18., kedd

Automatically loading a form "on demand"


Problem/Question/Abstract:

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:

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;

initialization
  RealForm2 := nil;
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 Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

Nincsenek megjegyzések:

Megjegyzés küldése