How to run FormClosing for ownerless forms when exiting red X?

I have a small application with several forms, each of which saves their panel layout during the FormClosing event.

Some forms should remain on the screen when the main form is minimized, so they are opened without an owner using form.Show() rather than form.Show(this) .

However, this affects the behavior of FormClosing - when a user exits red X, the FormClosing event FormClosing not FormClosing for orphaned forms.

Application.Exit() works as needed, but cancels the FormClosing event in the main form and calls Application.Exit () instead calls the FormClosing call twice on everything except forms without an owner.

I could probably repeat OpenForms in the FormClosing event of the main form and save whatever it takes to save, but that seems a bit hacky. Is there a way to make X behave the same as Application.Exit ()?

The following code demonstrates the problem:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Text = "Main"; Form ownedForm = new Form { Text = "Owned" }; ownedForm.FormClosing += (s, e) => { System.Diagnostics.Debug.WriteLine("FormClosing owned form"); }; ownedForm.Show(this); Form ownerlessForm = new Form { Text = "Ownerless" }; ownerlessForm.FormClosing += (s, e) => { System.Diagnostics.Debug.WriteLine("FormClosing ownerless form"); }; ownerlessForm.Show(); this.FormClosing += (s, e) => { System.Diagnostics.Debug.WriteLine("FormClosing main form"); // fix below doesn't work as needed! //if (e.CloseReason == CloseReason.UserClosing) //{ // e.Cancel = true; // Application.Exit(); //} }; } } 
+6
source share
1 answer

Add an event handler to the handler of the main FormClosing form to close the FormClosing forms when the main form is closed:

 ownerlessForm.Show(); //right after this line that you already have FormClosing += (s, e) => ownerlessForm.Close(); //add this 

This ensures that they will be closed gracefully and will have their closing events, instead of having the end of the main thread and causing the process to be torn down, preventing these forms from being gracefully closed.

+3
source

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


All Articles