默认情况下(也就是所有默认IDE配置设置),新设计的表单将自动创建。只有主表单会被显示,而次要表单可以通过以下方式显示:
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.Show;
Form3.ShowModal;
end;
通常情况下最好禁用自动创建选项。前往:工具 > (环境) 选项 > (VCL) 设计师 > 模块创建选项,然后禁用/取消勾选自动创建表单和数据模块选项。
相反,在需要时只创建一个已经设计好的表单:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm2;
begin
Form := TForm2.Create(Self);
Form.Show;
end;
这也说明了次要表单的全局变量是不必要的,良好的常规操作是尽快删除它们以防止错误使用:
type
TForm2 = class(TForm)
end;
implementation
如果您不想通过表单设计器设置这样的次要表单,那么您需要在运行时通过代码创建所有控件。具体步骤如下:
unit Unit2;
interface
uses
Classes, Forms, StdCtrls;
type
TForm2 = class(TForm)
private
FButton: TButton;
public
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
end;
implementation
constructor TForm2.CreateNew(AOwner: TComponent; Dummy: Integer = 0);
begin
inherited CreateNew(AOwner);
FButton := TButton.Create(Self);
FButton.SetBounds(10, 10, 60, 24);
FButton.Caption := 'OK';
FButton.Parent := Self;
end;
end.
正如你所看到的,我使用了 CreateNew
构造函数。这是 必要的,用于 T(Custom)Form
的派生类:
使用 CreateNew
来创建一个不使用相关联的 .DFM 文件初始化的表单。如果 TCustomForm
的后代不是 TForm
对象或 TForm
的后代,则始终使用 CreateNew
。
对于所有其他容器控件(例如 TPanel
、TFrame
等),可以重写默认的构造函数 Create
。
按以下方式调用此表单:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm2;
begin
Form := TForm2.Create(nil);
try
Form.ShowModal;
finally
Form.Free;
end;
end;
或者:
procedure TForm1.Button1Click(Sender: TObject);
begin
FForm := TForm2.CreateNew(Application);
FForm.Show;
end;
在这种情况下,当表单关闭时,它不会被释放,而是隐藏起来,因此您需要将其引用存储在私有字段(
FForm
)中,并稍后释放它。或者您可以自动完成此操作:
unit Unit2;
interface
uses
Classes, Forms, StdCtrls;
type
TForm2 = class(TForm)
private
FButton: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
public
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
end;
implementation
constructor TForm2.CreateNew(AOwner: TComponent; Dummy: Integer = 0);
begin
inherited CreateNew(AOwner);
OnClose := FormClose;
FButton := TButton.Create(Self);
FButton.SetBounds(10, 10, 60, 24);
FButton.Caption := 'OK';
FButton.Parent := Self;
end;
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
现在,您可以在不存储引用的情况下调用它:
procedure TForm1.Button1Click(Sender: TObject);
begin
TForm2.CreateNew(Self).Show;
end;
无论是将
Self
、
Application
还是
nil
作为新表单的所有者,取决于你希望何时在不手动释放或通过
OnClose
事件释放的情况下自动销毁它。使用:
Self
:当调用窗体被销毁时,将销毁新的窗体。当调用窗体不是主窗体时,这非常有用。
Application
:将在应用程序结束时销毁新窗体。这是我的首选。
nil
:将不会销毁新窗体,导致在应用程序完成时出现内存泄漏。不过,当Windows杀死进程时,内存最终会被释放。
Dialogs.CreateMessageDialog
以获取示例。 - NGLN