我有一个带有多个表单的小应用程序,每个表单在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, …Run Code Online (Sandbox Code Playgroud)