How do I avoid calling Application.CreateForm twice?

I came across this page Why shouldn't I call Application.CreateForm . Now I have a 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);

First, a splash shape is created, then a data module, and finally, the main shape. The page says that Application.CreateForm should not be called twice. Do I need to change the code above?

+5
source share
4 answers

There is nothing wrong with using Application.CreateForm several times. But this introduces global variables for each form, which may be the smell of code. Unfortunately, the IDE creates one for each form. Although you can delete them if you want.

- , , , . , Application.CreateForm .

. , .

, , Application.CreateForm, .

Application.CreateForm( ). , , Application.CreateForm.

, - , . .

+5

TClientData , TClientMainForm , ( , , FreeAndNil - ). . , , Application.CreateForm ( MainForm), :

  • , , Application.CreateForm - IDE.

  • , ( ) . ( Project | Options | Forms...) - " " " "

  • , TmyForm.Create() ( ..) Application.CreateForm(...). , , , ( , ), TmyForm.Create(nil) - - .

  • - , / , / ,

:

begin 
  Application.Initialize; 
  Application.MainFormOnTaskbar := True; 
  Application.CreateForm(TdmoMain, dmoMain); //<--this is a data module
  Application.CreateForm(TfrmMain, frmMain); //<--this will became the main form
  Application.CreateForm(TfrmAbout, frmAbout);
  //... other forms created here...
  frmMain.InitEngine; //<--initialization code. You can put somewhere else, according with your app architecture
  Application.Run;
end.

, , , .

+1

, DPR. , IDE DPR, , , . OnCreate , , , , , , .

, , CreateForm . . , CreateForm.

SplashForm := TSplashForm.Create(Application);
SplashForm.Show;
SplashForm.Update; // force update
Application.Initialize;

// Change to this.
ClientData := TClientData.Create(Application);

SplashForm.Update; // force update
Application.CreateForm(TClientMainForm, ClientMainForm);
Application.ShowHint := True;

Application.Run;
ClientMainForm.ServerConnected := false;

// Remove these.
FreeAndNil(ClientMainForm);
FreeAndNil(ClientData);

, , . Application, : FreeAndNil.

+1

. , Application.CreateForm

1) Datamodules: , , , . - Application.CreateForm. Datamodules, . , -, . .dpr

2) , ( , ...). , . , , , Microsoft Office, :)

, , , , "FreeAndNil". Dialog :

with TMyform.Create(nil) do
try
  //Setup
  case ShowModal of
    // Whatever return values you care about (if any)
  end;
finally
  Free;
end;

, , ...

0

All Articles