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?
Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client-side, Windows-based applications. Not only does Windows Forms provide many ready-to-use controls, it also provides the infrastructure for developing your own controls.
It provides a window handle ( hWnd ). Windows Forms controls use ambient properties so child controls can appear like their surrounding environment. An ambient property is a control property that, if not set, is retrieved from the parent control.
Show Method (System. Windows.
OnDestroy
event is fired from its BeforeDestruction
method.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With