如果用户单击“X”按钮,从子窗体关闭父窗体

5

我正在使用 WinForms。 我有两个表单,Form1(主要表单)和 Form2(子表单)。 当用户单击在 Form2 顶部的“X”按钮时,我想关闭 Form1。 在我的代码中,我试图通过 this.Owner.Close(); 来关闭 Form1,但这会引发错误。 为什么会出现这个错误,我应该如何在用户单击表单顶部的“X”按钮时从子表单关闭主表单。

错误

System.StackOverflowException 类型的未处理异常发生在 System.Windows.Forms.dll 中

enter image description here

表单 1

    private void btn_Open_Form2_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Owner = this;
        frm2.Show();
        this.Hide();
    }

表单2

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        this.Owner.Close();
    }

4
Application.Exit(); - Xaqron
2
你关闭了拥有者。这将关闭它所拥有的窗口。这将引发FormClosing事件。这将关闭拥有者。这将关闭它所拥有的窗口。这将引发FormClosing事件。这将关闭拥有者。这将关闭它所拥有的窗口。这将引发FormClosing事件。这将...崩溃。使用一个bool变量来打破递归。或者使用FormClosed事件。 - Hans Passant
你为什么要这样做呢?这不是良好的用户体验。 - CodingYoshi
@HansPassant 我明白了... 如果我在FormClosing事件中使用Application.Exit会更好吗? - taji01
2个回答

8
当您调用所有者的 Close 方法时,它会引发所拥有的表单的关闭事件处理程序,从而导致代码循环并导致堆栈溢出。您需要按以下方式更正代码:
void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    if(e.CloseReason!= CloseReason.FormOwnerClosing)
        this.Owner.Close();
}

如果您想在关闭拥有的窗体后关闭应用程序,您可以调用 Application.Exit 方法:
Application.Exit()

如果您需要告诉整个应用程序退出(这正是我在我的情况下所需的),那么Application.Exit()似乎更好。 - JSWulf

5

您需要从所属窗体(即Form1)的拥有窗体中删除Form2。然后您可以关闭Form1,而不会产生无限循环。

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    var form1 = Owner;
    form1.RemoveOwnedForm(this);
    form1.Close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接