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

0.00/5 (No votes)
28 Sep 2011CPOL 6.1K  
This example contains the code to manage the menu of open forms (standard Windows menu). When created, each mdi-child gets a menu item and event handler through which this element is removed from the menu when the corresponding form is closed.private void ShowOrCreateMdiChild(Type formType)...
This example contains the code to manage the menu of open forms (standard Windows menu). When created, each mdi-child gets a menu item and event handler through which this element is removed from the menu when the corresponding form is closed.
C#
private void ShowOrCreateMdiChild(Type formType) {
   foreach (Form frm in MdiChildren) {
      if (frm.GetType() == formType) {
         frm.Select();
         return;
      }
   }
   Form f = Activator.CreateInstance(formType) as Form;
   ShowMdiChild(f);
}

private void ShowMdiChild(Form form) {
   ToolStripMenuItem aWindowMenuItem = 
     new ToolStripMenuItem(form.Text, Bitmap.FromHicon(form.Icon.Handle));
   aWindowMenuItem.Tag = form;
   aWindowMenuItem.Click += new EventHandler(aWindowMenuItem_Click);
   m_windowsMenu.DropDownItems.Add(aWindowMenuItem);
   //m_windowsMenu - menu containing all MDI children
   form.FormClosed += new FormClosedEventHandler(mdiForm_FormClosed);
   form.MdiParent = this;
   form.Location = new Point(0, 0);
   form.Size = new Size(this.ClientSize.Width - 30, 
        this.ClientSize.Height - this.statusStrip1.Height - 30);
   form.StartPosition = FormStartPosition.Manual;
   form.Show();
   form.Select();
}

void mdiForm_FormClosed(object sender, FormClosedEventArgs e) {
   ToolStripItem itemToRemove = null;
   foreach (ToolStripItem mnu in m_windowsMenu.DropDownItems)
      if (mnu.Tag == sender) {
         itemToRemove = mnu;
         break;
      }
   if (itemToRemove != null)
      m_windowsMenu.DropDownItems.Remove(itemToRemove);
}

void aWindowMenuItem_Click(object sender, EventArgs e) {
   ToolStripMenuItem mnu = sender as ToolStripMenuItem;
   Form f = mnu.Tag as Form;
   if (f != null) {
      f.BringToFront();
      f.Focus();
   }
}

License

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