Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Single Instance Form in a MDI application

4.60/5 (5 votes)
2 Oct 2011CPOL 37.8K  
Single Instance Form in a MDI application
Sometimes, we want to ensure that only one instance of model's child form opens even if user clicks multiple times on the menu option in a MDI application. If form is already opened just set the focus on the form, otherwise create a new instance of the child form. Here is a quick tip to achieve this:

C#
public partial class MDIForm : Form
 {
    private Child1Form mChild1Form = null;
    private Child2Form mChild2Form = null;

    public MDIForm()
    {
       InitializeComponent();
    }

    private Form ShowOrActiveForm(Form form, Type t)
    {
       if (form == null)
       {
          form = (Form)Activator.CreateInstance(t);
          form.MdiParent = this;
          form.Show();
       }
       else
       {
          if (form.IsDisposed)
          {
             form = (Form)Activator.CreateInstance(t);
             form.MdiParent = this;
             form.Show();
          }
          else
          {
             form.Activate();
          }
       }
       return form;
    }

    private void newToolStripButton_Click(object sender, EventArgs e)
    {
       mChild1Form = ShowOrActiveForm(mChild1Form, typeof(Child1Form)) as Child1Form;
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
       mChild2Form = ShowOrActiveForm(mChild2Form, typeof(Child2Form)) as Child2Form;
    }
 }


I defined a function ShowOrActiveForm() and added private member variables for each child Form in MDIForm class which I want as single instance in MDI application. Child1Form and Child2Form are derived from Form class.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)