delphidelphi-10.2-tokyo

Disable Application.CreateForm with new form


I have a function which checks the settings and permissions before the start of the application, and if everything goes through, it selects what version to run and accordingly changes the main form.

function SomeControlFunction: Boolean;
var
  lMainForm : TForm;
begin
  if SomePermission then
    Application.CreateForm(TUForm1, lMainForm)
  else
    Application.CreateForm(TUForm2, lMainForm);
end;

Project.dpr

Application.Initialize;
if SomeControlFunction then
  Application.Run;

Unfortunately every time I create a new form in the project, it automatically adds to Project.dpr and I have to delete it every time. Is there any way to disable this behavior or is the whole process wrong and I should run the application differently?

Application.Initialize;
if SomeControlFunction then
  Application.CreateForm(TUNewForm, UNewForm);
Application.Run;

Solution

  • There is a work around to prevent the IDE from changing the dpr-file in that way.

    It seems that the Delphi IDE will explicitly look for places where the global variable Application from Vcl.Forms is used in the dpr-file and accordingly add the CreateForm calls.

    The standard template code in the dpr-file looks like this:

      Application.Initialize;
      Application.MainFormOnTaskbar := True;
      Application.CreateForm(TForm1, Form1);
      <-- new forms will be added here automatically
      Application.Run;
    

    If you use an 'alias' variable - lets say App - instead, the IDE will not interfere. Replace your existing code in the dpr-file with following:

    var
      App: TApplication;
    begin
      App := Application;
      App.Initialize;
      if SomeControlFunction then
        App.Run;
    end.
    

    Adding new Forms won't automatically add CreateForm calls in your dpr-file now.