Why is its own form destroyed after its own form?

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

Usually, I suggest that the owner destroy all his forms and then destroy himself.

Why such a procedure for the destruction of the form?

+5
source share
1 answer
  • An OnDestroy form event is fired from its BeforeDestruction method.
  • A component destroys the components belonging to it from its destructor.

The BeforeDestruction method is executed before the destructor and, therefore, the behavior that you observe.

In case the components belonging to him are destroyed before their owner. Imagine the opposite. If the owner was destroyed first, the list of components belonging to him would be destroyed, and there would be no way to destroy the components belonging to him.

What confuses you is that when the owner begins the process of destruction, a number of things happen before he reaches the point at which he will destroy any components that belong to him. And one of these things is to fire your own OnDestroy event.

The call tree for destroying the main form looks something like this:

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

By the time the main form called DestroyComponents from within its TComponent.Destroy , all its components were destroyed. Then the main form completes the destruction process, and then it is also destroyed.

+9
source

Source: https://habr.com/ru/post/1208667/


All Articles