Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a class as a parameter of a procedure in Delphi XE

what i need to do is something like this:

procedure A(type_of_form);
var form: TForm;
begin
  form := type_of_form.Create(application);
  form.showmodal;
  freeandnil(form);
end;

I did this for every dynamically created form:

form1 := TForm1.Create(application);
form1.showmodal;
freeandnil(form1);

What i will do inside procedure A is more complex, but the problem resides in how to make the creation of the form somewhat general. Perhaps something with @ operator... i really do not know.

Thanks for any suggestion!

like image 399
Speaker Avatar asked Dec 13 '11 19:12

Speaker


2 Answers

procedure Test(AMyFormClass: TFormClass);
var
 form: TForm;
begin
  form := AMyFormClass.Create(Application); // you can use nil if you Free it in here
  try
    form.ShowModal;
  finally
    form.Release; // generally better than Free for a Form
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Test(TForm2);
end;
like image 162
Francesca Avatar answered Nov 11 '22 08:11

Francesca


What you are asking for is basically what TApplication.CreateForm() does, eg:

Application.CreateForm(TForm1, form1); 
form1.ShowModal; 
FreeAndNil(form1); 

You can mimic that without calling TAppliction.CreateForm() like this:

procedure A(AClassType: TFormClass); 
var
  form: TForm; 
begin 
  form := AClassType.Create(Application); 
  try
    form.ShowModal; 
  finally
    FreeAndNil(form);
  end; 
end; 

...

begin
  A(TForm1); 
end;
like image 32
Remy Lebeau Avatar answered Nov 11 '22 07:11

Remy Lebeau