Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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

enter image description here

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();
    }
like image 593
taji01 Avatar asked Feb 13 '17 22:02

taji01


2 Answers

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 call Application.Exit methods:

Application.Exit()
like image 115
Reza Aghaei Avatar answered Sep 26 '22 20:09

Reza Aghaei


You should remove Form2 from owned forms of it's owner (i.e. 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();
}
like image 22
Sergey Berezovskiy Avatar answered Sep 23 '22 20:09

Sergey Berezovskiy