【发布时间】:2011-04-28 02:47:08
【问题描述】:
如何在 Delphi 中为 TFrame 模拟 OnDestroy 事件?
我在我的框架中添加了 constructor 和 destructor,认为这就是 TForm 所做的:
TframeEditCustomer = class(TFrame)
...
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
...
end;
constructor TframeEditCustomer.Create(AOwner: TComponent)
begin
inherited Create(AOwner);
//allocate stuff
end;
destructor TframeEditCustomer.Destroy;
begin
//cleanup stuff
inherited Destroy;
end;
问题在于,当我的析构函数运行时,框架上的控件已被销毁并且不再有效。
原因在于包含表单的析构函数,它用于触发OnDestroy 事件:
destructor TCustomForm.Destroy;
begin
...
if OldCreateOrder then DoDestroy; //-->fires Form's OnDestroy event; while controls are still valid
...
if HandleAllocated then DestroyWindowHandle; //-->destroys all controls on the form, and child frames
...
inherited Destroy; //--> calls destructor of my frame
...
end;
当窗体的析构函数运行时,我的框架对象的析构函数被调用。问题在于为时已晚。窗体调用DestroyWindowHandle,它要求Windows 销毁窗体的窗口句柄。这会递归地破坏所有子窗口 - 包括我框架上的那些。
所以当我的框架的destructor 运行时,我尝试访问不再处于有效状态的控件。
如何在 Delphi 中为 TFrame 模拟 OnDestroy 事件?
另见
【问题讨论】:
-
那些框架没有 OnCreate 和 OnDestroy 是设计使然。现在找不到帖子/文章/信息(所以是评论而不是答案),但我记得很久以前看到 borland 和/或 teamb 成员的回复(由 QC 编号见证)说明了这一点。 IIRC 的原因显然不是触发这些事件的好时机,可以确定为实例化的简单性和表单的破坏被流和可视表单/框架继承混淆了。
-
为什么不使用 OnCreate(由 borland 研发成员提供,由 TeamB 的 Jeff Overcash 转达):codenewsfast.com/isapi/isapi.dll/…。相同的推理可能适用于 OnDestroy 事件。因此,在制定您的解决方案时,我会注意这些注意事项。
标签: delphi destructor delphi-5 tframe