5
votes

I have a main form that creates a second form dynamically at runtime. When calling the create method the owner of the second form is set to the main form. When i close the application the FormDestroy of the main form is called before the FormDestroy of the second form.

Normally i would suggest that the owner destroys all owned forms and after that destroys itself.

Why is the form destruction order that way?

1

1 Answers

9
votes
  • A form's OnDestroy event is fired from its BeforeDestruction method.
  • A component destroys its owned components from its destructor.

The BeforeDestruction method executes before the destructor and hence the behaviour that you observe.

It is the case that owned components are destroyed before their owner. Imagine it was the other way around. If the owner was destroyed first, the list of owned components would have been destroyed and there would be no way to destroy the owned components.

What is confusing you is that when an owner begins its destruction process, a number of things happen before it reaches the point where it destroys any owned components. And one of those things is to fire its own OnDestroy event.

The call tree for the main form's destruction looks a little like this:

TMainForm.BeforeDestruction
  TCustomForm.BeforeDestruction
    TCustomForm.DoDestroy
      TMainForm.FormDestroy  --> this is your main form's OnDestroy event handler
TMainForm.Destroy
TForm.Destroy
....
TComponent.Destroy
  DestroyComponents;         --> owned components are destroyed here
....

By the time the main form has called DestroyComponents from inside its TComponent.Destroy, all the owned components have been destroyed. Then the main form completes its destruction process and then it too has been destroyed.