Search code examples
formsdelphidelphi-10.1-berlin

Create secondary form before main form while keeping FormMain as main form?


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?


Solution

  • 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;