Closing the stack close form

I have a problem in WinForms. I have created MDIParent-Form and I am calling ChildForm from Load MDFParent. And I want that if ChildForm is closed, MDIParent should close and application exits. This is why I wrote an event for childForm in MDIParent so that if ChildForm closes FormClosed-Event it will fire in MDIParent, but it will throw an exception. I know there is an infinite loop, but I don't know why ...

   private void MDIParent1_Load(object sender, EventArgs e)
    {
        Form1 childForm = new Form1();
        childForm.MdiParent = this;
        childForm.FormClosed += childForm_FormClosed;
        childForm.Show();
    }

    void childForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.Close(); 
        //{Cannot evaluate expression because the current thread is in a Qaru state.}
    }

      

but if i use

  Application.Exit();

      

instead this.Close()

... everything works fine ... I want to know why ... can someone explain?

Update: I tried the same without MDIParent and everything works ... but why is there a problem if I use MDIParent

+3


source to share


1 answer


This is a bit of a bug, the problem is that the child is still present in the collection MDIParent1.MdiChildren

when the FormClosed event is raised. In other words, the FormClosed event fires too early. So when you close the parent, it will try to close the child again. Raises the FormClosed child event again. Which closes the parent again. Etcetera. The order in which events are fired will never be a problem. Well, let's call it a bug :)

A workaround is to use the Disposed event instead:



private void MDIParent1_Load(object sender, EventArgs e)
{
    Form1 childForm = new Form1();
    childForm.MdiParent = this;
    childForm.Disposed += childForm_Disposed;
    childForm.Show();
}

void childForm_Disposed(object sender, EventArgs e)
{
    this.Close();   // Fine now
}

      

+4


source







All Articles