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);
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();
}
}