Search code examples
c#winformsmdi

Layout remaining forms when a form closes


I have a MdiParent that opens multiple instances of a form as its MdiChildren. When each form is opened, I call this.LayoutMdi(MdiLayout.TileHorizontal); to lay out all forms.

What I want to do is do the same thing for when a form closes but I can't do it in the MdiChildren's FormClosing or FormClosed event handlers because it still includes the closed form when laying out the forms (even though it's not shown)

Any ideas on how to get this accomplished, perhaps in the MdiParent?


Solution

  • Keep track of the children in the MdiParent form, and then wire up a Disposed handler:

    private List<Form> _childForms = new List<Form>();
    
    protected override void OnMdiChildActivate(EventArgs e)
    {
        base.OnMdiChildActivate(e);
    
        Form f = ActiveMdiChild;
        if (f == null)
            return;
        else
        {
            if (!_childForms.Contains(f))
            {
                _childForms.Add(f);
                f.Disposed += new EventHandler(childForm_Disposed);
            }
        }
    }
    
    private void childForm_Disposed(Object sender, EventArgs e)
    {
        _childForms.Remove((Form)sender);
        this.LayoutMdi(MdiLayout.TileHorizontal);
    }