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;