模式窗体与非模式窗体

非模式窗体从创建到销毁都需要代码来维护,防止内存未安全释放。

模式窗体就比较省心一些,只需要在代码段的try…finally中创建并维护即可。

下面用例子来说明一下两类窗体如何调用:

 

主窗体程序:

unit Main;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls,ModalForm,ModalessForm;



type

  TForm8 = class(TForm)

    Button1: TButton;

    Button2: TButton;

    procedure Button2Click(Sender: TObject);

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;



var

  Form8: TForm8;



implementation



{$R *.dfm}



procedure TForm8.Button1Click(Sender: TObject);

begin

  try

    Form9:=TForm9.Create(Application);

    Form9.ShowModal;

  finally

    Form9.Free; //窗体的清理放在同一代码段的try...finaally中,而不是在ModalForm中的Destroy方法里。

    Form9:=nil;

  end;



end;



procedure TForm8.Button2Click(Sender: TObject);

begin

  if not Assigned(Form10) then  //防止出现多个窗体实例

  Form10:=TForm10.Create(Application); //窗体的创建方式



  Form10.Show;

end;



end.

模式窗体:
 
unit ModalForm;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs;



type

  TForm9 = class(TForm)

  private

    { Private declarations }

  public

    { Public declarations }

  end;



var

  Form9: TForm9;



implementation



{$R *.dfm}





end.

 

非模式窗体:

unit ModalessForm;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs;



type

  TForm10 = class(TForm)

    procedure FormClose(Sender: TObject; var Action: TCloseAction);

    procedure FormDestroy(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;



var

  Form10: TForm10;



implementation



{$R *.dfm}



procedure TForm10.FormClose(Sender: TObject; var Action: TCloseAction);

begin

  Action:=caFree;

end;



procedure TForm10.FormDestroy(Sender: TObject);

begin

  Form10:=nil; //这里是Form10设为nil而不是TForm10,否则将无法再次创建窗体。

end;



end.

你可能感兴趣的:(模式)