【问题标题】:Close Parent Form from Child Form if user clicks on the "X" button如果用户单击“X”按钮,则从子表单关闭父表单
【发布时间】: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 会更好吗?

标签: c# .net winforms


【解决方案1】:

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

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

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

Application.Exit()

【讨论】:

  • Application.Exit() 如果您需要告诉整个应用程序退出似乎更好(这正是我所需要的)
【解决方案2】:

您应该将Form2 从其所有者的所有表单(即Form1)中删除。然后你可以关闭Form1而不进行无限循环

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

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多