5

I have a problem in WinForms. I created a MDIParent-Form and i call a ChildForm from the Load of the MDIParent. And I want that if the ChildForm closes, the MDIParent must close and the Application exits. Thats why i wrote an event for the childForm in the MDIParent, so that if the ChildForm closes the FormClosed-Event would be fired in the MDIParent, but it throws a stack overflow exception. I know that there is a infinite loop, but I dont 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 stack overflow state.}
    }

but if i use

  Application.Exit();

instead of this.Close()... everything works fine ... i want to know why...can someone explain??

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

4
  • 4
    You have an infinite loop: if the form is closed by any event, it will tell the form to close, which will trigger the event again, and try to close again. Commented May 2, 2015 at 21:22
  • why does it work if I dont use MDIParent ?? Commented May 2, 2015 at 21:24
  • 1
    Maybe when you call this.Close(), it calls close on all the child forms, which in turn calls childForm_FormClosed and that's your infinite recursion? I'm almost certain Memphy's explanation is correct. Commented May 2, 2015 at 21:27
  • 2
    If you close the parent, doesn't the children get closed as well? That would explain your infinite loop Commented May 2, 2015 at 21:27

1 Answer 1

6

This is a bit of a bug, the problem is that the child still is present in the MDIParent1.MdiChildren collection when the FormClosed event fires. In other words, the FormClosed event fires a little too soon. So when you close the parent, it will try to close the child again. Which triggers the child's FormClosed event again. Which closes the parent again. Etcetera. Event firing order is never not a problem. Well, let's call it a bug :)

The workaround is to use the Disposed event instead, it fires later:

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.