首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >这段代码是在FormClose中空指针的正确过程吗?

这段代码是在FormClose中空指针的正确过程吗?
EN

Stack Overflow用户
提问于 2018-06-02 18:37:38
回答 2查看 217关注 0票数 0

IDE: Delphi XE6。

我的主窗体创建另一个窗体,该窗体创建TFormZoom的一个实例。一切似乎都运行得天衣无缝。

我只想确保我在FormClose中清空指针的过程没有扭曲Delphi的一些内部工作。

procedure TFormZoom.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;

  // if I did not set it to nil here, the next time I would create this form I would get
  // EAccessViolation, because my other code checks for this form <> nil ...

  FormZoom := nil;
end;

我现在在想,这个方法是不是好。我没有得到任何编译,也没有运行时错误,这个问题只是一个技术问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-02 20:16:39

如果您在TFormZoom.FormCloseend;处设置了断点,并使用F8单步执行调用onclose事件处理程序的VCL代码,您将看到它是从TCustomForm.DoClose调用的,而之前是从TCustomForm.Close调用的。此时,可以看到以下代码(在Delphi 10.2.3中)

DoClose(CloseAction);
if CloseAction <> caNone then
if Application.MainForm = Self then Application.Terminate
else if CloseAction = caHide then Hide
else if CloseAction = caMinimize then WindowState := wsMinimized
else Release;

因为您将Action var设置为caFree,这意味着表单的.Release将由VCL代码调用。我的结论是:将全局变量FormZoom设置为nil,不会造成任何问题。

票数 2
EN

Stack Overflow用户

发布于 2018-06-03 04:33:51

有时OnClose事件可能根本不会触发。因此,除了设置Action := caFree;之外,我还会将其他代码移到OnCloseQuery或OnDestroy事件中。

FormZoom := nil;

在我看来,必须是在OnDestroy事件中,因为如果表单变量已经为空,则可能会有一些其他事件,例如控件上的事件,在关闭期间运行并导致访问冲突。

票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50656011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档