Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put code to execute once after my Delphi app has finished initialising?

I have functions I want to perform after my app has finished initialising and the main form has been created. I did have the code (call it ProcedureX) in the forms OnShow event, but I have just noticed that it is being called twice, because OnShow is firing twice. It fires when the main program DPR calls:

Application.CreateForm(TMainForm, MainForm) ;  

as I would expect. But after that, when I read stuff from an INI file that includes the forms on-screen position, I have a call:

MainForm.position := poScreenCenter ;

This, it would appear fires the OnShow event again.

Where can I put my call to ProcedureX, which must only be called once, and which needs the main form to be created before it can execute?

like image 744
rossmcm Avatar asked Sep 23 '10 22:09

rossmcm


2 Answers

If your code only needs to run once per form creation (or per application and the form is only created once per application run), put the code in the form's OnCreate handler. It is the natural place for it to go.

Nowadays (since D3 I think) the OnCreate fires at the end of the construction process in the AfterConstruction method. Only if you were to set OldCreateOrder to True (and it is False by default), might you get in trouble as that makes the OnCreate fire at the end of the Create constructor.

like image 101
Marjan Venema Avatar answered Sep 21 '22 09:09

Marjan Venema


The normal order of execution for a Form is :

  • AfterConstruction: when the form and it components are fully created with all their properties.
  • OnShow: whenever the Form is ready to show (and, yes, any change causing a CM_SHOWINGCHANGED can trigger an OnShow)
  • Activate: whenever the Form takes the Focus

So, depending on what you need in ProcedureX, AfterConstruction might be enough, and is executed only once; just override it and add ProcedureX after inherited. It'll be after OnCreate.

If it is not the case, you can post a custom message to your Form from AfterConstruction, it will be queued and will reach your custom handler after the other messages have been handled.

In both cases, you would not need a extra boolean Field.

like image 40
Francesca Avatar answered Sep 22 '22 09:09

Francesca