Click here to Skip to main content
15,881,139 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Single Instance Form in a MDI application

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
2 Oct 2011CPOL 37.3K   9   2
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)


Written By
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.

Comments and Discussions

 
QuestionUse generic Pin
Member 779439829-Aug-14 3:43
Member 779439829-Aug-14 3:43 
GeneralReason for my vote of 5 Specially for use of CreateInstance.... Pin
Shlabh Sharma27-Sep-11 2:23
Shlabh Sharma27-Sep-11 2:23 

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

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