我正在使用 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
表格 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/