簡體   English   中英

如果用戶單擊“X”按鈕,則從子窗體關閉父窗體

[英]Close Parent Form from Child Form if user clicks on the “X” button

我正在使用WinForms。 我有2個表格,Form1 (主表格)和Form2 (兒童表格) 當用戶點擊form2頂部的“X”按鈕時,我想關閉form1。 在我的代碼中,我試圖通過說this.Owner.Close();來關閉form1 this.Owner.Close(); 但它會引發錯誤。 為什么拋出此錯誤,以及當用戶單擊表單頂部的“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();
    }

窗體2

    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()

您應該從其擁有者的所有形式(即Form1)中刪除Form2 然后你可以關閉Form1而沒有無限循環

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM