Exiting the Program

One of the most common program actions is pressing the Cancel button to quit the program. Unfortunately, this is one of the most poorly documented features of many languages.

Visual Basic | Delphi


Visual Basic 6.0

There are several ways to exit programs. One alternative is to add the following code to either the Cancel button or the File/Exit menu selection
  ' Quit the application
  Private Sub Cancel_UIButton_Click()
    Unload Me   ' If there are no problems, 
                '   this stops this application
                '   and triggers code in the 
                '   Unload, QueryUnload, and Terminate events
    End         ' Otherwise, this forces the application to quit
  End Sub
Notice that, by itself, the End command stops program execution and that code placed in the Unload, QueryUnload, and Terminate events of forms and class modules is not executed.

Alternatively,

    Unload SomeName_UIForm
could be used to terminate a named form.

The Cancel button's Cancel property should be set to True so that the Esc key will activate it.


Delphi

To stop a Delphi VCL (windows) application use one of the following When you click the 'x' in the title bar, choose Close from the form's System menu, Windows generates a Close message which eventually calls the Close method of the active form. (The same method called by the Close commands above.)

Both OnCloseQuery and OnClose return a value by modifying a parameter. (Events can not return values like a function.) This provides 2 events that you can use to control whether or not a form should be closed. For instance, you can use either of these to ask the user to save changes.

If you use Application.Terminate, then onCloseQuery and onClose will not be called.

The Halt procedure performs an abnormal termination and no additional code is executed.

In a dialog box, the Cancel button's Cancel property should be set to True so that the Esc key will activate it. Then add the following to the OnClick event.

  procedure TForm2.Cancel_UIButtonClick(Sender: TObject);
  begin
    Close;
  end;

When a form is being created and its Visible property is True, the following events occur in the order listed:

  1. OnCreate
  2. OnShow
  3. OnActivate
  4. OnPaint
The Close method has no effect in OnCreate, but works fine in OnShow. If you have to, Application.Terminate will work in OnCreate.


Author: Robert Clemenzi - clemenzi@cpcug.org
URL: http:// cpcug.org / user / clemenzi / technical / Languages / ProgramExit.htm