Skip to content

How to terminate your Delphi application before it starts

It sounds like a contradiction: Why would you start you application and terminate it right away? Well, sometimes we can only "really" launch our main form if certain requirements are met.

  • Does my configuration file exist?
  • Can I connect to the database?
  • Do other data files exist?
  • Do my image resources exist?
  • Is the hardware sufficient?
  • ...

About the video

In all of these cases you might want to display an error message but not launch your application as a consequence. With Delphi VCL applications, it may seem simple at first. However, there is some housekeeping required in order to stop execution correctly.

The latest episode of "How it Works With Holger" gives you all the essential info you need.

TL;DR

In order to check requirements before launching your application, proceed as follows:

  1. Create a new unit with TAppController. The application controller will launch the application or terminate if necessary.

  2. In this example, the TDataController class uses a SQLite database that needs to exist. Otherwise, the application cannot be run. Thus, the method CanStartApp checks if the file exists. It will be called by TAppController before the main window of the application is shown.

    class function TDataManager.CanStartApp: Boolean;
    begin
      Result := TFile.Exists( GetDatabaseFilename );
    end;
    

  3. The key of this concept is that the code from the DPR of your default VCL Windows Form application is moved into the Run method of the application controller.

    class procedure TAppController.Run;
    var
      LMainForm: TFrmMain;
    
    begin
      {$IFDEF DEBUG}
      ReportMemoryLeaksOnShutdown := True;
      {$ENDIF}
    
      Application.Initialize;
      Application.MainFormOnTaskbar := True;
    
      if TDataManager.CanStartApp then
      begin
        Application.CreateForm(TFrmMain, LMainForm);
        LMainForm.Manager := TDataManager.Create( LMainForm );
        Application.Run;
      end
      else
      begin
        ShowMessageFmt( 'Database file missing (%s). Application will terminate.',
          [ TDataManager.GetDatabaseFilename ] );
      end;
    end;
    

  4. It is checked if TDataManager.CanStartApp is True. Otherwise, a message is shown. Note that Application.Run is not called.

  5. The source code in the DPR project file can be reduced to:

    begin
       TAppController.Run;
    end.