Monday, August 20, 2007

Merging Menu and Toolbar to MDI Form

I have a form that it is used both stand alone and within an MDI from. When used in an MDI form I wanted to move the menu's and toolbars to the shared placed on the MDI form whereas using it on a standalone case I had no option than having it on the owner form.

To establish this behavior I had to implement the activate and deactivate methods to make the toolstrip and menu strip, which hold the toolbar items and menu items, invisible and move the items to the new container. This is a stait forward solution as illustrated below:



private void OnFormActivate(object sender, EventArgs e)
{
try
{
// Get the parent
Form parent = this.MdiParent;
if (parent == null)
return;

// Get the toolbar on the parent by name
string targetToolbar = "toolStrip"; // using the name of the control
if (!parent.Controls.ContainsKey(targetToolbar))
return;
ToolStrip target
= parent.Controls[targetToolbar] as ToolStrip;
if (target == null)
return;

ToolStripManager.Merge(
this.toolStrip1, target);

// Hide the original container
this.toolStrip1.Visible = false;
this.menuStrip1.Visible = false;
SetToolbarCaption();
}
catch { } // Any exception will cause the toolbar to remain on its oroginal parent
}
private void OnFormDeactivate(object sender, EventArgs e)
{
try
{
// Get the parent
Form parent = this.MdiParent;
if (parent == null)
return;

// Get the toolbar on the parent by name
string targetToolbar = "toolStrip";
if (!parent.Controls.ContainsKey(targetToolbar))
return;

// Double check
ToolStrip target = parent.Controls[targetToolbar] as ToolStrip;
if (target == null)
return;

// Actual Merge Revert of the contents of the toolStrip
ToolStripManager.RevertMerge(target, this.toolStrip1);

// Keep hiding the original container
this.toolStrip1.Visible = false;
}
catch { }
}


All I need to do next is to wire these events to the propper events: FormActivate and Deactivate.

No comments: