参看TApplication的CreateForm就可以了:
注意:如果关闭Form2的时候释放了内存,要
Form2 := nil;
否则会出错。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TMainForm = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
procedure CreateForm(InstanceClass: TComponentClass;
var Reference);
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses Unit2;
{$R *.DFM}
procedure TMainForm.CreateForm(InstanceClass: TComponentClass;
var Reference);
var
Instance: TComponent;
begin
if TComponent(Reference) <> nil then
exit;
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(MainForm);
except
TComponent(Reference) := nil;
raise;
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
CreateForm(TForm2,Form2);
Form2.Show();
end;
end.