3
votes

In the Delphi 10.1 Berlin IDE, with a VCL Form application project, in the Project Options dialog, I have these settings:

enter image description here

Now I want the formOptions Form to be created BEFORE the FormMain Form while keeping the FormMain Form as the Main Form. The reason is: The main form could load data in its FormCreate procedure (where formOptions still has not been created), but to process these data it needs the settings from the formOptions form.

But as soon as I drag the formOptions item to the top of the list, also the main form combobox above changes to formOptions!

So how can I make the formOptions Form to be created BEFORE the FormMain Form while keeping the FormMain Form as the Main Form?

1
Remove it from the auto-list, and use formOptions := TformOptions.Create instead of Application.CreateForm.Sertac Akyuz
You mean in the DPR project file?user1580348
This works. So I do have to use nil as AOwner because the main form has not yet been created: formOptions := TformOptions.Create(nil);. Is using nil as owner a correct procedure and do I have to destroy formOptions manually at program end?user1580348
Auto-created forms use Application as the Owner. If you use a nil Owner instead, you must manually Free the Form.Remy Lebeau

1 Answers

11
votes

The first TForm that is created with Application.CreateForm() becomes the VCL's Application.MainForm, and cannot be changed. So do whatever initializations you need to do before CreateForm() assigns the MainForm.

You have two options:

  1. Remove formOptions from the auto-create list (thus removing the generated CreateForm() call for it), and then create it manually yourself in code. CreateForm() does not assign the MainForm until it is fully created, so you can actually handle this in one of two different ways:

    a. directly in the project's .dpr file :

    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    formOptions := TFormOptions.Create(Application);
    Application.CreateForm(TFormMain, FormMain);
    Application.Run;
    

    b. in the MainForm's OnCreate event:

    procedure TFormMain.FormCreate(Sender: TObject);
    begin
      formOptions := TFormOptions.Create(Application); // or even Self
    end;
    
  2. move your shared settings to a TDataModule (or even a standalone class) instead, and then (auto-)create that object before creating either of the Forms. FormMain and formOptions can then retrieve their settings from that object when needed:

    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    Application.CreateForm(TSettingsDM, SettingsDM);
    Application.CreateForm(TFormMain, FormMain);
    Application.CreateForm(TFormOptions, formOptions);
    Application.Run;