Search code examples
c#winformsmdi

Change LayoutMdi from parent form when closing child form


I'm currently working with forms and mdi. In my project there is a mainform (a mdiContainer) which can have x subforms. I want to reach, that everytime, a subform is closed, all other subforms where arranged again.

You can do that with writing this into the mainform:

public void resetToolStripMenuItem_Click(object sender, EventArgs e)
{
  this.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical);
}

In the subform, i do this:

private void subform_FormClosed(object sender, FormClosedEventArgs e)
{
  try
  {
    Form1 mainform = new Form1();
    mainform.resetToolStripMenuItem_Click(mainform, EventArgs.Empty);
  }
  catch
  {
    System.Windows.Forms.MessageBox.Show("error");
  }
}

It does not give any error, but also wont arrange the subforms again. I also tried to call the method with other parameters.

Any idea how i can make this work?


Solution

  • This line should make you pause:

    Form1 mainform = new Form1();
    

    You made a new form, so you aren't referencing the existing one.

    But I think there are issues trying to do this from the child form.

    It's probably better to listen to the Closed event of the child from the MDIParent, like this:

    ChildForm childForm = new ChildForm();
    childForm.FormClosed += childForm_FormClosed;
    childForm.MdiParent = this;
    childForm.Show();
    

    And then in the Closed method, call the code:

    void childForm_FormClosed(object sender, FormClosedEventArgs e) {
      this.BeginInvoke(new Action(() => { 
        resetToolStripMenuItem_Click(null, null);
      }));
    }
    

    I used BeginInvoke because otherwise, the closed child form is still being included in the layout tiling.