开发者

How i can to make a procedure for create a form?

I have this procedure :

procedure TForm1.Button1Click(Sender: TObject);
var
   a:TForm2;
begin
    a := TForm2.Create(Self);
    a.Parent := ScrollBox1;
    a.Align := alClient;
    a.Show;
    a.SetFocus;
end;

And i change that above code to this, but i receive a error, Why? I must change this code to?

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
     Mak开发者_如何学CeAform(Tform2,Self,Panel1,alClient);
end;


Your original code passes a class (TForm2) to a procedure which receives an instance (aForm). Indeed this instance is not even initialised but that's not actually your problem here.

What you need to do is to receive, in MakeAform, a class rather than an instance.

Your code should be:

//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;

A couple more points:

  1. What is the purpose of a.SetFocus? I wasn't aware that a form could hold the focus.
  2. If you don't intend to re-parent this form after constructing it then you may as well do away with the Owner parameter and let the Parent own the form.


A better way of doing this is to declare a class procedure in Form2 and then call that prpocedure on Form1. Ej

TForm2
    ...
    public 
      class procedure ShowForm;
    end;

class procedure TForm2.ShowForm;
begin
  with TForm2.Create(Application) do begin
    ShowModal;
    Free;
  end;
end;

And, in Form1.ButtonClick(...). you just can write:

TForm2.ShowForm;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜