How to bring MDI Child Form To Front?

suchislife picture suchislife · Dec 12, 2014 · Viewed 10.6k times · Source

Overview:

I have an MDI Parent Form in which I load other forms. After loading the second form, I can no longer bring the first one to the front.

Description:

On the parent form I have a menu strip containing 2 menu items; Home and Search. Each click event loads their corresponding form unless said form is already loaded.

The problem:

a. Click Search. Then click Home.

b. If Search is once again clicked, it no longer brings its corresponding, already opened form to the front.

    private void tsmHome_Click(object sender, EventArgs e)
    {
        // Loop through all open forms...
        foreach (Form form in Application.OpenForms)
        {
            // If frmHome is Opened, set focus to it and exit subroutine.
            if (form.GetType() == typeof(frmSearch))
            {

                form.Activate();
                return;
            }
        }

        // If frmHome is not Opened, create it. 
        frmHome f = new frmHome();
        f.MdiParent = this;
        f.Show();
    }

    private void tsmSearch_Click(object sender, EventArgs e)
    {
        // Loop through all open forms...
        foreach (Form form in Application.OpenForms)
        {
            // If frmSearch is Opened, set focus to it and exit subroutine.
            if (form.GetType() == typeof(frmSearch))
            {

                form.Activate();
                return;
            }
        }

        // If frmSearch is not Opened, create it. 
        frmSearch f = new frmSearch();
        f.MdiParent = this;
        f.Show();
    }

Answer

Mark Hall picture Mark Hall · Dec 12, 2014

Your code is working for me.. After changing one line in your tsmHome_Click event handler

You had.

if (form.GetType() == typeof(frmSearch))

It should be.

if (form.GetType() == typeof(frmHome))

Looks like a copy paste error got you.