- 作者:xiaoxiao
- 发表时间:2020-12-23 11:02
- 来源:未知
我们在用delphi 编制程序时,常常需要消除同一窗体的二次创建,这样,既节省了系统资源有在一定程度上美化了程序界面,其实这很简单,我们一起来动手试一下吧!
首先,我们要创建一个主窗体,并命名为MainForm,在主窗体上面放一个按钮Button1.
然后在创建一个窗体,命名为SecondForm,并在菜单Project|Options...设置它的创建方式为available forms.
切换到MainForm的单元文件,在菜单中选择File|Use Unite...,在弹出的对话框中选择SecondForm的单元文件Unit2,然后点击OK键。
好了,下面我们来写代码了。
双击Button1,并添加下面代码:
if SecondForm=nil thenbegin?? 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.
///全文结束