Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Single Instance Form in a MDI application

, 28 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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.
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)

Share

About the Author

Vladimir Vorobiev

United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 29 Sep 2011
Article Copyright 2011 by Vladimir Vorobiev
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid