c# - 如果用户单击 "X"按钮,则从子窗体关闭父窗体

标签 c# .net winforms

我正在使用 WinForms。我有 2 个表格,表格 1 (主表格) 和表格 2 (子表格)。当用户单击 form2 顶部的“X”按钮时,我想关闭 form1。在我的代码中,我试图通过说 this.Owner.Close(); 来关闭 form1,但它会引发错误。为什么会抛出此错误,以及当用户单击窗体顶部的“X”按钮时如何从子窗体关闭主窗体。

错误

An unhandled exception of type 'System.StackOverflowException' occurred in 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();
    }

Form2

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

最佳答案

当您调用 Close 时所有者的方法,它会引发所拥有表单的关闭事件处理程序,这样代码就会形成一个循环,导致堆栈溢出。您需要以这种方式更正代码:

void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    if(e.CloseReason!= CloseReason.FormOwnerClosing)
        this.Owner.Close();
}

如果你想在关闭拥有的表单后关闭应用程序,你可以调用Application.Exit方法:

Application.Exit()

关于c# - 如果用户单击 "X"按钮,则从子窗体关闭父窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214403/

相关文章:

c# - 最大化表单,并禁止用户调整表单大小

c# - 如何使 Assert.AreEqual 通过 POCO

c# - 如何防止 .NET 应用程序从 GAC 加载/引用程序集?

使用 NLog 进行日志记录所需的 C# 派生类类型

c# - 在 instagram 中获取用户 ID

c# - 更新记录

c# - 如何克隆微软图表控件?

mysql - 关于创建面向看板 winapp 的信息

c# - 根据到达时间和旅行时间计算发射时间

C# 运算符重载 == 和 pragma 警告 660 & 661 在不相关时不覆盖 Equals 和 GetHashCode