Question

Create form with parameter name and send parameter to this form

I read a file that has the name of the form I need to create. After the form is created, before the ShowModal(), I need to send parameters to this form.

If the form name were fixed, I would use the Create() constructor and pass the parameters using Create().

How do I create a TForm with a name that comes in a variable, and pass parameters to it?

I'm creating the TForm like this, but I can't pass the parameter:

procedure TFrmTeste.CriaForm( FormName: String);
var
  FrmClass: TFormClass;
  Frm: TForm;
begin


  FrmClass := TFormClass( FindClass( FormName ));
  Frm := FrmClass.Create(Application);

  // ** Here I need to pass parameters **

  frm.ShowModal;
end;
 3  104  3
1 Jan 1970

Solution

 11

You can still use a custom constructor without having to specify a fixed class type in the code. Simply create a base class derived from TForm and add whatever extra functionality you need to it, and then define a new metaclass type to use instead of TFormClass. And then derive your real Form(s) from this base class. The trick is the base class constructor must be virtual and override'n in the derived classes in order to create instances of them via the metaclass.

For example:

type
  TBaseForm = class(TForm)
  public
    constructor Create(AOwner: TComponent; ... Parameters ...); virtual;
  end;

  TBaseFormClass = class of TBaseForm;

...

constructor TBaseForm.Create(AOwner: TComponent; ... Parameters ...);
begin
  inherited Create(AOwner);
  // use Parameters as needed...
end;
type
  TMyRealForm = class(TBaseForm)
  public
    constructor Create(AOwner: TComponent; ... Parameters ...); override;
  end;

constructor TMyRealForm.Create(AOwner: TComponent; ... Parameters ...);
begin
  inherited Create(AOwner, ... Parameters ...);
  // use Parameters as needed...
end;
procedure TFrmTeste.CriaForm(const FormName: String);
var
  FrmClass: TBaseFormClass;
  Frm: TForm;
begin
  FrmClass := TBaseFormClass( FindClass( FormName ));
  Frm := FrmClass.Create(Application, ... Parameters ...);
  Frm.ShowModal;
end;

Alternatively, a different option is to use an interface instead, then you don't need a custom base class, eg:

type
  IMyInterface = interface(IInterface)
    ['{FDCA8BF0-342A-4BC5-BFC5-9F39EBB352C0}'] 
    procedure SetParams(... Parameters ...);
  end;
type
  TMyRealForm = class(TForm, IMyInterface)
  public
    procedure SetParams(... Parameters ...);
  end;

procedure TMyRealForm.SetParams(... Parameters ...);
begin
  // use Parameters as needed...
end;
procedure TFrmTeste.CriaForm(const FormName: String);
var
  FrmClass: TFormClass;
  Frm: TForm;
  Intf: IMyInterface;
begin
  FrmClass := TFormClass( FindClass( FormName ));
  Frm := FrmClass.Create(Application);
  if Supports(Frm, IMyInterface, Intf) then
    Intf.SetParams(... Parameters ...);
  Frm.ShowModal;
end;
2024-07-17
Remy Lebeau