Terminating an Application when using Delphi

Sometimes there are reasons to terminate an application due to unforeseeable issues and there has been a lot of talk how to handle this event. Let’s go over a simple application and break down what needs to be done.

Go to the code

The initial code opens up a splash screen, displays it and finally releases it after a few moments.

      
      Splashscreen.Show;
      Splashscreen.Update;
      Sleep(2000);
      Splashscreen.Free;
      Application.Initialize;

The application defaults are set with the title and the help file as well as creating the data module along with the login screen.

  Application.DefaultFont.Name := 'Arial';
  Application.MainFormOnTaskBar := True;
  Application.Title := 'Application Name';
  Application.HelpFile := ExtractFilePath(Application.ExeName) + 'Help.CHM';
  Application.CreateForm(TDM, DM);
  Application.CreateForm(TfrmLogin, frmLogin);

The application at this point will open up the login screen allowing the user to enter their information. The license is also checked at this stage to see if the client has a valid license.

If the license is invalid a mrCancel is set back from the login screen after the user was notified that the license was invalid. At this point the important steps is to release the data module and terminate the application.

The application ProcessMessages permits the application to process messages that are currently in the message queue. ProcessMessages cycles the Windows message loop until it is empty, and then returns control to the application. It is just a method to clean up everything before exiting the application.

Finally you will see if everything is fine you can open up the main form. On a note concerning releasing objects. During a debug session, not releasing the data module would actually show an issue.

  ValidLicense := frmLogin.ShowModal;
  frmLogin.Free;
  if (ValidLicense = mrCancel) then
  begin
    DM.Free;
    Application.Terminate;
    Application.ProcessMessages;
  end
  else
  begin
    Application.CreateForm(TfrmMainForm, frmMainForm);
    Application.Run;
  end;

Things can be done differently within the application if there is a fatal event by simply closing the main form and cleaning up any open objects.

Baron Software

There has been discussion in stackoverflow on this matter.

Calling Terminate allows the application to shut down in an orderly fashion. Terminate calls the Windows API PostQuitMessage function to perform an orderly shutdown of the application.

Finally, the key when leaving an application after a fatal issue is to clean up. Freeing objects, closing databases will make the application follow good guidelines.