Fabio Vitale
Fabio Vitale

Reputation: 2287

Application.Terminate doesn't

If I call Application.Terminate OR Application.MaiForm.Close inside a method. the application doesn't terminate!

procedure doSomething;
var
  ErrorFound: boolean;
begin
  [...]
  try
    if ErrorFound then
      Application.Terminate;
  finally
  [...]
  end;
end;

I cannot understand why.

Please note that I'm calling Application.Terminate from inside a Try...Finally block, in the Try section.

Upvotes: 4

Views: 5988

Answers (2)

Robin Qiu
Robin Qiu

Reputation: 5731

Inspired by David Heffernan's answer above, (https://stackoverflow.com/a/8078808/1041047), I added a line of code after TApplication.Terminate:

Application.Terminate;

Application.ProcessMessages;

and it works.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612934

Most likely you are calling Application.Terminate from a busy loop that itself does not terminate. If you enter an event handler but never return from it then calling Application.Terminate or Application.MainForm.Close would indeed be futile. These routines that close an application are cooperative. They post messages to the main message loop requesting that the application gracefully shuts down.

For example, the following code would exhibit the symptoms you describe:

procedure TMyForm.Button1Click(Sender: TObject);
begin
  while True do
    Application.Terminate;
end;

Another (more likely) possibility is that you are calling this function from inside a modal form but not closing the modal form.

Unless you show more code, we are reduced to making guesses like this.

Upvotes: 8

Related Questions