Click here to Skip to main content
Click here to Skip to main content

Single Instance Form in a MDI application

By , 2 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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.

License

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

About the Author

Manish K. Agarwal
Software Developer (Senior) Oracle
India India
Working with Oracle. Using C/C++, VC++, MFC, STL, C#, Java etc. on various platform like Windows, Unix, Macintosh etc. from last 13+ years to convert various type of requirements into running software components. My core expertise is multithreaded desktop product and large scale enterprises software development.
Follow on   LinkedIn

Comments and Discussions

 
GeneralReason for my vote of 5 Specially for use of CreateInstance.... PinmemberShlabh Sharma27-Sep-11 2:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 2 Oct 2011
Article Copyright 2011 by Manish K. Agarwal
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid