简体   繁体   中英

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

I'm using WinForms. I have 2 forms, Form1 (main form) and Form2 (Child Form) . I want to close form1 when the user clicks on the "X" button up at the top of form2. In my code I'm trying to close form1 by saying this.Owner.Close(); but it throws an error. Why is it throwing this error, and how can i close the main form from the child form when the user clicks on the "X" button at the top of the form.

Error

An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll

在此输入图像描述

Form 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();
    }

When you call Close method of the owner, it raise closing event handler of owned forms and this way the code makes a loop causing stack overflow. You need to correct the code this way:

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

If you want to close the application after closing the owned form, you can use:

Application.Exit()

You should remove Form2 from owned forms of it's owner (ie Form1). Then you can close Form1 without infinite loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM