How to check Windows form is already open

Suppose if we are calling a form from a menu click on MDI form, then we need to create the instance declaration of that form at top level like this:

Form1 fm = null;

Then we need to define the menu click event to call the Form1 as follows:

private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (fm == null|| fm.Text=="")
    {
        fm = new Form1();
        fm.MdiParent = this;
        fm.Dock = DockStyle.Fill;
        fm.Show();
    }
    else if (CheckOpened(fm.Text))
    {
        fm.WindowState = FormWindowState.Normal;
        fm.Dock = DockStyle.Fill;
        fm.Show();
        fm.Focus();
    }
}

The CheckOpened defined to check the Form1 is already opened or not:

private bool CheckOpened(string name)
{
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm.Text == name)
        {
            return true;
        }
    }
    return false;
}

Hope this will solve the issues on creating multiple instance of a form also getting focus to the Form1 on menu click if it is already opened or minimized.
Ebook Download
View all
Learn
View all