Delphi中动态创建窗体有四种方式

时间:2023-03-08 20:14:59
Delphi中动态创建窗体有四种方式

Delphi中动态创建窗体有四种方式,最好的方式如下:

比如在第一个窗体中调用每二个,主为第一个,第二个设为动态创建

Uses Unit2; //引用单元文件

procedure TForm1.Button1Click(Sender: TObject);
begin
form2:=TForm2.Create(Application); //创建窗体
form2.Show; //显示窗体
end;
end.

======================================================

最好不要用另外三种:

Application.CreateForm(TForm2,Form2);

form2:=TForm2.Create(Self);

form2:=TForm2.Create(nil);

Delphi窗体创建大揭密

1. 窗体权限的转移实验

新建3个Form , 在Project->Options… 中的Forms 一页把Form2和Form3 放置在 Available forms中,保留Form1在Auto-create forms中,让Form1在程序一开始运行就创建。

在Form1(主窗体)中的OnCreate()事件函数中加入以下代码:

procedure TForm1.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form1 Create Completed!;

Form1.Show;

Application.CreateForm(TForm2, Form2);

end;

(代码2)

在Form2的OnCreate()事件函数中加入以下代码:

procedure TForm2.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form2 Create Completed!;

Form2.Show;

Application.CreateForm(TForm3,Form3);

end;

(代码3)

在Form3的OnCreate()事件函数中加入以下代码:

procedure TForm2.FormCreate(Sender: TObject);

begin

Label1.Caption:=Form3 Create Completed!;

Form3.Show;

end;

(代码4)

这个程序在运行后将显示三个窗体,分别是Form1,Form2,和Form3。你可能在想,如果要关闭程序,只要关闭Form1这个主窗体就可以了。然而你错了,应该是关闭Form3才能将整个程序关闭。为什么呢?关键在CreateForm()这个窗体创建函数,查一下Delphi的随机帮助文件就清楚了。帮助文件有关CreateForm()函数的说明如下:

Call CreateForm to dynamically create a form at runtime. Developers do not need to add code for creating most forms, because typically one or more calls to CreateForm are added automatically to the projects main source when using the form designer.

CreateForm creates a new form of the type specified by the FormClass parameter and assigns it to the variable given by the Reference parameter. The owner of the new form is the Application object.

Note: By default, the form created by the first call to CreateForm in a project becomes the application’s main form.