Delphi中避免创建重复窗体

我们在用delphi 编制程序时,常常需要消除同一窗体的二次创建,这样,既节省了系统资源有在一定程度上美化了程序界面,其实这很简单,我们一起来动手试一下吧!

首先,我们要创建一个主窗体,并命名为MainForm,在主窗体上面放一个按钮Button1.

然后在创建一个窗体,命名为SecondForm,并在菜单Project|Options...设置它的创建方式为available forms.

切换到MainForm的单元文件,在菜单中选择File|Use Unite...,在弹出的对话框中选择SecondForm的单元文件Unit2,然后点击OK键。

好了,下面我们来写代码了。

双击Button1,并添加下面代码:

if SecondForm=nil then
begin
?? SecondForm:=TSecondForm.Creat(Self);
?? SecondForm.Show;
end;

在SecondForm的onClose事件中添加以下代码:

Action:=caFree;

在SecondForm的onDestroy事件中添加以下代码:

SecondForm:=nil;

好了,运行一下程序试一下,是不是达到了我们的效果,以下是完整的代码:

///Unit1.pas

unit Unit1;

interface

uses
? Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
? Dialogs, StdCtrls;

type
? TMainForm = class(TForm)
??? Button1: TButton;
??? procedure Button1Click(Sender: TObject);
? private
??? { Private declarations }
? public
??? { Public declarations }
? end;

var
? MainForm: TMainForm;

implementation

uses Unit2;

{$R *.dfm}

procedure TMainForm.Button1Click(Sender: TObject);
begin
? if SecondForm=nil then
? begin
??? SecondForm:=TSecondForm.Create(Self);
??? SecondForm.Show;
? end;
end;

end.
///Unit2.pas///

?

unit Unit2;

interface

uses
? Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
? Dialogs;

type
? TSecondForm = class(TForm)
??? procedure FormClose(Sender: TObject; var Action: TCloseAction);
??? procedure FormDestroy(Sender: TObject);
? private
??? { Private declarations }
? public
??? { Public declarations }
? end;

var
? SecondForm: TSecondForm;

implementation

{$R *.dfm}

procedure TSecondForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
?Action:=caFree;
end;

procedure TSecondForm.FormDestroy(Sender: TObject);
begin
? SecondForm:=nil;
end;

end.

///全文结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值