Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an owned form destroyed after the owner form itself?

Tags:

forms

delphi

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?

like image 515
Sebastian Schülke Avatar asked Dec 09 '14 14:12

Sebastian Schülke


People also ask

What is control in WinForms?

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.

What is the use of control class in windows form creation?

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.

Which method is used to display the control to the user?

Show Method (System. Windows.


1 Answers

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

like image 168
David Heffernan Avatar answered Sep 18 '22 18:09

David Heffernan