user1593881
user1593881

Reputation:

Application.CreateForm() forms visibility / state

What's the state of forms created using the TApplication.CreateForm() when creating a multiform VCL applications? Is there a call to a WinAPI that sets them to an invisible state or is it handled by some VCL inner workings?

  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.CreateForm(TForm2, Form2); // Invisible
  Application.CreateForm(TForm3, Form3); // Invisible
  Application.Run;

Upvotes: 1

Views: 2812

Answers (2)

IceCold
IceCold

Reputation: 21212

This article speaks about the dangers of accessing the form instance in its own OnCreate event handler. One way to avoid this is to refrain to doing any initialization in main form's OnCreate handler. Wait until main form is truly ready. For this send a message to your self. Something like this:

const 
   MSG_LateInitialize= WM_APP + 4711;

TMainForm = class(TForm)
    ...
    procedure LateInitialize(var Message: TMessage); message MSG_LateInitialize;
 end;

procedure TMainForm.FormCreate (Sender: TObject);
begin
 { Send custom message to self }
 PostMessage(Self.Handle, MSG_LateInitialize, 0, 0);
end;

procedure TMainForm.LateInitialize; { This is called only after the main form was fully created }
begin
  init stuff here...
end;

It works as long as you don't use the "magic" of Application.ProcessMessage during your app initialization (Hey! Stop using it, not only during your app initialization. Don't use it at all!).


PS: If you look above, there is a lot of boilerplate code necessary to have a basic/correct initialization in place. If Delphi pretends to be safe and easy to use (which it kinda does) it should have provided this kind of functionality for beginners, (hidden) under the hood. Something like a function called AfterApplicationInitialized or AfterFormTrullyCreated :)

Upvotes: 0

mghie
mghie

Reputation: 32344

The first form that is created using Application.CreateForm() will become the application's MainForm, and will be shown automatically by Application.Run() if Application.ShowMainForm is true, the MainForm's WindowState is not wsMinimized, and the process was not created with the SW_SHOWMINNOACTIVE flag specified.

All other forms created by Application.CreateForm() will be shown automatically only if their Visible property is set to True. By default, the IDE sets the Visible property for secondary Forms to False.

Please note that auto-creating all Forms on application startup is usually not a good idea. You should remove the second and third Forms from the auto-create list in the Project Options, and then dynamically create them in code when they are actually needed. You can even set your IDE to not auto-create secondary Forms by default.

Upvotes: 5

Related Questions