Search code examples
delphi

Which is the best place to initialize code in VCL forms?


Possible Duplicate:
Splash Screen Programatically
Show a splash screen while a database connection (that might take a long time) runs

Which is the best place to initialize code such as loading INI file? I want first to show the form on screen so the user know that the app is loading and ONLY after that I want to call lengthy functions such as LoadIniFile or IsConnectedToInternet (the last one is REALLY slow).

The OnCreate is not good because the form is not yet ready and it will not show up on screen.

I do this I DPR but not working always:

program Test;
begin
  Application.Initialize;
  Application.Title := 'Test app';
  Application.CreateForm(TfrmTest, frmTest);
  frmTest.Show;               <---------------------- won't show
  LateInitialize;
  Application.Run;
end.

The form will not show until LateInitialize (4-5 seconds) is executed.


procedure LateInitialize;
begin
 CursorBussy;
 TRY
  // all this won't work also. the form won't show
  frmTest.Visible:= TRUE;
  Application.ProcessMessages; 
  frmTest.Show;
  Application.ProcessMessages;
  frmTest.BringToFront;
  frmTest.Update;
  Application.ProcessMessages;
  
  DoSomethingLengthy;     {4-5 seconds}
 FINALLY
  CursorNotBussy;
 END;
end;     <--------- Now the form shows.

And yes, frmTest it is my only form (the main form).


Solution

  • An easy way to do this, is to send a message to yourself. I do this all the time

    const
      MSG_AFTERCREATE = WM_APP + 4711;
    
    ...
    procedure OnCreate(Sender: TObject);
    procedure AfterCreate(var message: TMessage); message MSG_AFTERCREATE;
    ...
    
    
    Implementation
    
    procedure OnCreate(Sender: TObject);
    begin
      PostMessage(Self.Handle, MSG_AFTERCREATE, 0, 0);
    end;
    
    procedure AfterCreate(var message: TMessage);
    begin
      //Do initializing here... the form is done creating, and are actually visible now...
    end;