How to Prevent Multiple Instances of Child Form in MDI Windows Form Application

Introduction


This is common problem for beginners while working with MDI form. Multiple instances of the form will open when we try to open it with Form.Show() method. 

This article will show how to overcome with this problem.




Technology

CSharp 2.20/3.5

Implementation

For preventing multiple instances of child form we can use ShowDialog() method. But it will be problematic to user because if user wants to work with many windows at a time he can not because he need to close opened window if he opened it with ShowDialog() method.

So lets implement some code that will open new window, if there is no child window opened before. And if its opened previously then application will just focus that window and will not create any new child windows.
   
private void button1_Click(object sender, EventArgs e)
{
    bool IsOpen = false;
    foreach (Form f in Application.OpenForms)
    {
        if (f.Text == "Form2")
        {
            IsOpen = true;
            f.Focus();
            break;
        }
    }
 
    if (IsOpen == false)
    {
        Form2 f2 = new Form2();
        f2.MdiParent = this;
        f2.Show();
    }
}

Understanding the code

Here we have declared one variable that is used as flag for the child window is already opened or not? This flag will store the status of child form :)

Now we iterate through each opened form in our application and check if any form with Form2 is already opened or not. If it is found, then we set flag to true and focus() that already opened form and break the loop.

Now we are checking status of flag. If application sees that flag is still false after iterating then it will create a new instance of that child window :)

That's it you are done !

Conclusion

We have just see in this article how to prevent multiple instances of child form in MDI windows Form application.


Similar Articles