2017-02-13 101 views
4

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

错误

类型 'System.StackOverflowException' 的未处理的异常发生在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(); 
    } 

窗体2

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

'Application.Exit();' – Xaqron

+1

你关闭主人。这将关闭其拥有的窗户。这将引发FormClosing事件。这将关闭所有者。这将关闭其拥有的窗户。这将引发FormClosing事件。这将关闭所有者。这将关闭其拥有的窗户。这将引发FormClosing事件。哪个... Kaboom。使用* bool *变量来中断递归。或FormClosed事件。 –

+0

你为什么要这么做呢?这不是好用户体验。 – CodingYoshi

回答

6

当失主的Close方法,提高成交独资形式的事件处理程序,这样的代码使循环导致堆栈溢出。你需要正确的代码是这样的:

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

如果你想关闭关闭所有的表格后的应用程序,你可以使用:

Application.Exit() 
+0

如果你需要告诉整个应用程序退出(这是我需要的),Application.Exit()似乎更好。 – JSWulf

2

你应该从它拥有的形式取出Form2的主人(即Form1中)。然后你就可以关闭Form1没有无限循环

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