如何避免两次调用Application.CreateForm? [英] How do I avoid to call Application.CreateForm twice?

查看:78
本文介绍了如何避免两次调用Application.CreateForm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了此页面为什么我不应该给Application.CreateForm打电话
现在我有这样的代码:

I stumbled on this page Why shouldn’t I call Application.CreateForm. Now I have some code like this:

SplashForm := TSplashForm.Create(Application);
SplashForm.Show;
SplashForm.Update; // force update
Application.Initialize;
Application.CreateForm(TClientData, ClientData);
SplashForm.Update; // force update
Application.CreateForm(TClientMainForm, ClientMainForm);
Application.ShowHint := True;

Application.Run;
ClientMainForm.ServerConnected := false;
FreeAndNil(ClientMainForm);
FreeAndNil(ClientData);

首先创建一个初始窗体,然后创建一个数据模块,最后创建主窗体。该页面说Application.CreateForm不应被调用两次。上面的代码是否应该更改?

First a splashform is created, then a datamodule and last the main form. The page says that Application.CreateForm should not be called twice. Should the code above be changed?

推荐答案

多次使用Application.CreateForm并没有错。但这会为每种形式引入全局变量,这可能是代码的味道。
不幸的是,IDE为每个表单创建了一个表单。虽然可以根据需要删除它们。

There is nothing wrong with using Application.CreateForm multiple times. But this introduces global variables for each form which can be a code smell. Unfortunately the IDE creates one for each form. Although you can remove them if you like.

更好的方法是在需要时创建表单,并在准备就绪后释放它。因此,您仅将Application.CreateForm用于主窗体。

A better way is to create a form when you need it and release it when you are ready with it. So you only use Application.CreateForm for the main form.

可以通过主窗体创建主数据模块。

A main datamodule can be created by the main form. But it can be global too, just a matter of taste.

因此,要回答这个问题,您可以通过在本地创建和释放表单来避免使用Application.CreateForm。

So to answer the question, you can avoid Application.CreateForm by creating and releasing the forms locally.

本文提到了Application.CreateForm的副作用(第一个完成的表单是主表单)。
因此,如果主窗体使用Application.CreateForm创建其他窗体,则可能会产生意外的副作用。

The article mentions the side effect of Application.CreateForm (the first completed form is the main form). So there can be unexpected side effects if the main form creates other forms using Application.CreateForm.

因此,为了避免任何讨厌的事情,应将自己的权限限制为一个电话。仅使用一种全局形式即可完成。

So just to avoid any nastyness, you should limit yoursef to a single call. Which is done using only one global form.

这篇关于如何避免两次调用Application.CreateForm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆