delphitform

Free an object in OnClose event of TForm


I am new to Delphi and my question may be very basic.

I created a Form in a Delphi procedure. Until now, I was using ShowModal() and then freeing all the objects that I want to avoid leaking after closing the Form.

Now, I would like to show the Form modeless, but I don't know how I can free the objects inside the OnClose event.

Does anybody know a solution for it?


Solution

  • Simply set the Action parameter to caFree:

    procedure TMyForm.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      Action := caFree;
    end;
    

    Per the documentation:

    The value of the Action parameter determines if the form actually closes. These are the possible values of Action:

    caNone
    The form is not allowed to close, so nothing happens.

    caHide
    The form is not closed, but just hidden. Your application can still access a hidden form.

    caFree
    The form is closed and all allocated memory for the form is freed
    .

    caMinimize
    The form is minimized, rather than closed. This is the default action for MDI child forms.

    Setting Action to caFree will cause the Form to call Release() on itself after the OnClose handler has exited:

    Destroys the form and frees its associated memory.

    Use Release to destroy the form and free its associated memory.

    Release does not destroy the form until all event handlers of the form and event handlers of components on the form have finished executing. Release also guarantees that all messages in the form's event queue are processed before the form is released. Any event handlers for the form or its children should use Release instead of Free (Delphi) or delete (C++). Failing to do so can cause a memory access error.

    Note: Release returns immediately to the caller. It does not wait for the form to be freed before returning.

    Release() posts a delayed CM_RELEASE message to the Form window. Once execution flow returns to the main message loop and the message is dispatched, the Form will free itself from memory.

    If your TForm object owns other objects, they will be freed automatically when the TForm is freed.