Introduction
Multi Document Interface (MDI) tab page browsing has been very popular among many Windows applications especially internet browsers such as Opera, Mozilla, Maxthon and many others. After failing to find an article on it, I decided to write one myself to show any interested reader that creating an MDI tab page browsing can be done with pretty simple but neat coding. All that is needed is a little creativity.
Using the code
The source code is a template of the tab page window application. The template can be used for creating a tab-page capable window program.
The code
First, in the parent form, set the IsMDIContainer
property to true
. Attach a TabControl
component to the form and set the Dock
property to Top
.
Next, in the child form, create a non-initialized TabControl
and a TabPage
. Create a property for these two objects. Later, we will see that these two objects will contain references to the TabControl
in the parent form and the corresponding child TabPage
.
private TabControl tabCtrl;
private TabPage tabPag;
public TabPage TabPag
{
get
{
return tabPag;
}
set
{
tabPag = value;
}
}
public TabControl TabCtrl
{
set
{
tabCtrl = value;
}
}
When the MDI child form is closing, destroy the corresponding tab page.
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.tabPag.Dispose();
if (!tabCtrl.HasChildren)
{
tabCtrl.Visible = false;
}
}
When the MDI child form is activated, activate the corresponding tab page.
private void MDIChild_Activated(object sender, System.EventArgs e)
{
tabCtrl.SelectedTab = tabPag;
if (!tabCtrl.Visible)
{
tabCtrl.Visible = true;
}
}
When the child form is created, add the reference values of the TabControl
and TabPage
to its fields.
private void NewMenuItem_Click(object sender, System.EventArgs e)
{
MDIChild childForm = new MDIChild();
childForm.Text = "MDIChild " + childCount.ToString();
childForm.MdiParent = this;
childForm.TabCtrl = tabControl1;
TabPage tp = new TabPage();
tp.Parent = tabControl1;
tp.Text = childForm.Text;
tp.Show();
childForm.TabPag = tp;
childForm.Show();
childCount++;
tabControl1.SelectedTab = tp;
}
When a tab page is selected, activate its corresponding MDI child form.
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
foreach (MDIChild childForm in this.MdiChildren)
{
if (childForm.TabPag.Equals(tabControl1.SelectedTab))
{
childForm.Select();
}
}
}
That's all!