65.9K
CodeProject is changing. Read more.
Home

Single Instance Form in a MDI application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (5 votes)

Sep 20, 2011

CPOL
viewsIcon

37897

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:
  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.