我有这个程序:
procedure TForm1.Button1Click(Sender: TObject);
var
a:TForm2;
begin
a := TForm2.Create(Self);
a.Parent := ScrollBox1;
a.Align := alClient;
a.Show;
a.SetFocus;
end;
我将上面的代码更改为此,但是我收到错误,为什么? 我必须将此代码更改为?
procedure TForm1.MakeAform(aForm:Tform;Cmp:TComponent;Parent1:TWinControl;Align1:TAlign);
var
a:aForm; // Error Here
begin
a := aForm.Create(Cmp);
a.Parent := Parent1;
a.Align := Align1;
a.Show;
a.SetFocus;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MakeAform(Tform2,Self,Panel1,alClient);
end;
答案 0 :(得分:5)
您的原始代码将类(TForm2)传递给接收实例(aForm)的过程。事实上,这个实例甚至没有初始化,但实际上这不是你的问题。
您需要做的是在MakeAform中接收一个类而不是一个实例。
您的代码应为:
//note, in Forms.pas the type TFormClass is defined as:
// TFormClass = class of TForm;
//
//A variable of TFormClass holds a class (rather than an instance)
//and that class must be derived from TForm.
procedure TForm1.MakeAform(
FormClass: TFormClass;
Owner: TComponent;
Parent: TWinControl;
Align: TAlign
);
var
a: TForm;
begin
a := FormClass.Create(Owner);
a.Parent := Parent;
a.Align := Align;
a.Show;
a.SetFocus;
end;
还有几点:
答案 1 :(得分:1)
更好的方法是在Form2中声明一个类过程,然后在Form1上调用该prpocedure。 EJ
TForm2
...
public
class procedure ShowForm;
end;
class procedure TForm2.ShowForm;
begin
with TForm2.Create(Application) do begin
ShowModal;
Free;
end;
end;
并且,在Form1.ButtonClick(...)中。你可以写:
TForm2.ShowForm;