【发布时间】:2017-07-02 01:11:03
【问题描述】:
我正在使用 WinForms。我有 2 个表单,Form1 (主表单) 和 Form2 (子表单)。当用户单击form2顶部的“X”按钮时,我想关闭form1。在我的代码中,我试图通过说 this.Owner.Close(); 来关闭 form1,但它会引发错误。为什么会抛出这个错误,当用户点击表单顶部的“X”按钮时,如何从子表单关闭主表单。
错误
System.Windows.Forms.dll 中出现“System.StackOverflowException”类型的未处理异常
表格 1
private void btn_Open_Form2_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.Show();
this.Hide();
}
Form2
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.Owner.Close();
}
【问题讨论】:
-
Application.Exit(); -
您关闭了所有者。这将关闭其拥有的窗口。这将引发 FormClosing 事件。这将关闭所有者。这将关闭其拥有的窗口。这将引发 FormClosing 事件。这将关闭所有者。这将关闭其拥有的窗口。这将引发 FormClosing 事件。其中... Kaboom。使用 bool 变量来中断递归。或 FormClosed 事件。
-
你为什么要这样做?这不是好的用户体验。
-
@HansPassant 我明白了...如果我只在 FormClosing 中使用 Application.Exit 会更好吗?