Search code examples
delphifiremonkeydelphi-xe5firemonkey-fm3

Delphi XE5 - Waiting for TForm.OnCreate() finish components' population


I'd like to check from Form1.OnCreate event handler procedure if Form1 constructor Create finished the job with populating all the components on Form1. Then would like to use Form1 to loop through the components and change Text property. I have tried:

WHILE NOT Assigned(Form1) DO 
  Sleep(100); 

... but it didn't work.

Now when I try to use Form1, I get Access Violation error.


Solution

  • The OnCreate event is triggered at the end of the construction of a Form object. A Form's components are created during the construction process before the OnCreate event is triggered. There is no need to "check .. if Form1 constructor Create finished the job" as that is basically guaranteed. Once OnCreate is triggered, you can access the components.

    If your Form1 object is created via TApplication.CreateForm() at program startup then the Form1 variable will be assigned a valid but uninitialized object before the constructor is called, and thus will point at a valid object in the OnCreate event.

    If your Form1 object is created by calling its constructor in your code, then the Form1 variable will not be assigned until after the constructor exits, and thus will not point at a valid object in the OnCreate event.

    Either way, you should not be using the Form1 variable inside of the OnCreate event for the Form1 object to begin with. Use the Self pointer instead, or typecast the event's Sender parameter. Both will point at the same Form1 object that was created.