【发布时间】:2025-12-03 11:40:02
【问题描述】:
我有一个包含多个表单的小应用程序,每个表单都会在 FormClosing 事件期间保存其窗格布局。
当主窗体最小化时,某些窗体需要保留在屏幕上,因此它们以 form.Show() 无主打开,而不是 form.Show(this)。
但这会影响FormClosing 的行为 - 当用户使用红色 X 退出时,FormClosing 事件不会为无主表单触发。
Application.Exit() 确实可以根据需要工作,但取消主窗体中的 FormClosing 事件并调用 Application.Exit() 会导致 FormClosing 在除无主窗体之外的所有内容上被调用两次。
我可能会在主窗体的 FormClosing 事件中迭代 OpenForms 并保存需要保存的任何内容,但这似乎有点 hack。有没有办法让 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();
//}
};
}
}
【问题讨论】: