Notification的应用

本文探讨了在Delphi中动态创建窗体并在FormCreate事件中关闭窗体时遇到的问题及解决方案。通过对比Self.Close与PostMessage两种方法,分析了它们在窗体关闭时的行为差异及其背后的原因。

原文出处:
  http://topic.youkuaiyun.com/t/20060729/23/4914257.html

原文摘要:
  问题提出:  
  从MainForm动态创建一个Form(已经设计好的),代码为:  
  if   (NOT   Assigned(ActiveForm))   then  
       ActiveForm:=   TActiveForm.Create(Application);  
  if(Assigned(ActiveForm))   then  
       ActiveForm.Show()  
  当调试运行后从ActiveForm的FormCreate()事件中直接使用Self.Close()关闭ActiveForm后,再次执行上述创建窗体的代码后发生错误, 并强制关闭。     
  解决方法:  
  在ActiveForm的FormCreate()事件中使用PostMessage来关闭窗体。代码:  
  Windows.PostMessage(Self.Handle,   WM_CLOSE,   0,   0);  
   
  问题:  
  虽然关闭窗体的问题已经解决了,但是其中一些具体细节还不知道。为什么Self.Close()会发生错误,而 PostMessage()却可以正常执行 ?  为什么是第二次时发生错误而不是第一次时???  
  FormCreate()事件中一般会有一些初始化的代码,并且一个Form一般都会有一些组件,当从FormCreate()中直接 关闭时,是不是因为某些 组件未能正常初始化或释放而发生错误?如果这样理解的话,PostMessage()是不是提供了一个缓冲时间,来完成FormCreate()事件后再关闭Form? 

精华代码:

unit Unit2;

interface  
   
uses  
    Windows,   Messages,   SysUtils,   Variants,   Classes,   Graphics,   Controls,   Forms,  
    Dialogs,   StdCtrls;  
   
type  
    TFoo   =   class;  
    TForm2   =   class(TForm)
        Button1:   TButton;  
        procedure   Button1Click(Sender:   TObject);  
        procedure   FormCreate(Sender:   TObject);  
        procedure   FormDestroy(Sender:   TObject);  
    private  
        Foo:   TFoo;  
        {   Private   declarations   }  
    public  
        {   Public   declarations   }  
    end;

    TFoo   =   class(TComponent)  
    private  
          FForm:TForm;  
          function   GetForm:   TForm;
    public  
          procedure  Notification(AComponent: TComponent; Operation: TOperation); override;
   
    end;  
var
    Form2:   TForm2;

implementation  
   
{$R   *.dfm}  
   
function   TFoo.GetForm:   TForm;  
var   S:String;  
begin  
    if Assigned(FForm)   then
        Result   :=   FForm
    else  
    begin  
        FForm:=TForm.Create(nil);  
        Result:=FForm;  
        FForm.FreeNotification(Self);
    end;  
end;

procedure   TFoo.Notification(AComponent: TComponent; Operation: TOperation);
begin
    inherited;
    if(AComponent=FForm) and ( Operation = opRemove)   then
    begin
       FForm:=nil
    end;
end;

procedure   TForm2.Button1Click(Sender: TObject);
var   AForm:TForm;  
begin  
        AForm:=Foo.GetForm;  
        AForm.ShowModal;
        FreeAndNil(AForm);  
end;  
   
procedure   TForm2.FormCreate(Sender:   TObject);
begin  
    Foo:=TFoo.Create(Self);
end;  
   
procedure   TForm2.FormDestroy(Sender:   TObject);
begin  
    Foo.free;  
end;

end.

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值