Close parent form from child form if user clicks "X"

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

Error An unhandled exception of type "System.QaruException" 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();
    }
+4
source share
2 answers

Close , , , . :

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

, Application.Exit :

Application.Exit()
+6

Form2 (.. Form1). Form1

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

Source: https://habr.com/ru/post/1669636/


All Articles