Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - stop the application on the main form create

The situation is the following one: on the application main form create event some conditions are not respected, so the application needs to close.

Yes, this is a bad design but how the application should be closed? Using the Application.MainForm.Close generates an AV. Application.Terminate is not a very good choice. Other ideas?

like image 264
RBA Avatar asked Jul 30 '13 11:07

RBA


People also ask

How do I close an application in Delphi?

To perform a normal termination of a Delphi application, call the Terminate method on the global Application object. If the application does not use a unit that provides an Application object, call the Exit procedure from the main Program block.

How do you make a main form in Delphi?

To assign a different form to the MainForm property, select the form on the Project > Options > Forms dialog box at design time. MainForm cannot be modified at run time (it is read-only at run time). Note: By default, the form created by the first call to CreateForm in a project becomes the application's main form.


3 Answers

Application.Terminate works just fine. However, keep in mind that it is a delayed termination, all it does is posts a WM_QUIT message to the calling thread's message queue, so the app will not actually terminate until Application.Run() is called to start processing the main thread's message queue. Because of that, you might see the MainForm flicker onscreen momentarily before the app is actually terminated. If you want to avoid that, you can set the Application.ShowMainForm property to false, eg:

procedure TMainForm.FormCreate(Sender: TObject);
begin
  if (some condition) then
  begin
    Application.ShowMainForm := False;
    Application.Terminate;
  end;
end;

However, as others have stated, a better design is to do the check in the project's DPR file instead and not even create the MainForm at all if necessary, eg:

Application.Initialize;
if not (some condition) then
begin
  Application.CreateForm(TMainForm, MainForm);
  Application.Run;
end;
like image 53
Remy Lebeau Avatar answered Sep 30 '22 15:09

Remy Lebeau


Well if you want to stick to your bad design, here's a bad answer:

try
  Application.Terminate
except
end;
like image 38
Pieter B Avatar answered Sep 30 '22 14:09

Pieter B


Application.Terminate

is good enough unless you care to refine your design to check these conditions before the form is created (in the dpr).

like image 39
Sam Avatar answered Sep 30 '22 14:09

Sam