- 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.