[英]How to fire FormClosing for ownerless forms on red X exit?
我有一個帶有多個表單的小應用程序,每個表單在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();
//}
};
}
}
向主窗體的FormClosing
處理程序添加一個事件處理程序,以在主窗體關閉時關閉無主窗體:
ownerlessForm.Show(); //right after this line that you already have
FormClosing += (s, e) => ownerlessForm.Close(); //add this
這將確保它們正常關閉,並且將關閉事件,而不是使主線程結束並且在不讓這些形式正常關閉的情況下拆除該過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.