如何在红色X出口处为无主表单启动FormClosing?

jlm*_*lmt 6 c# winforms

我有一个带有多个表单的小应用程序,每个表单在FormClosing事件期间保存它们的窗格布局.

当主窗体最小化时,某些窗体需要保留在屏幕上,因此它们是无主打开的form.Show(),而不是form.Show(this).

但是这会影响FormClosing行为 - 当用户使用红色X退出时,FormClosing不会为无主表单触发事件.

Application.Exit()确实可以根据需要工作,但是FormClosing在主窗体中取消事件并调用Application.Exit()会导致FormClosing在除无主窗体之外的所有内容上调用两次.

我可以在主窗体的FormClosing事件中迭代OpenForms并保存任何需要保存的东西,但这看起来有点像黑客.有没有办法使X的行为与Application.Exit()相同?

以下代码演示了此问题:

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();
            //}
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 3

将事件处理程序添加到主窗体的FormClosing处理程序以在主窗体关闭时关闭无主窗体:

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

这将确保它们优雅地关闭,并且运行它们的关闭事件,而不是让主线程结束并让进程被拆除而不让这些表单优雅地关闭。