Saturday, January 19, 2008

Handling .NET Toolstrip merge and unmerge in C#

The Tool strip control that ships with VS2005 allows you to create a Windows™ style tool bar for your MDI Applications. This control works well with one exception: automatic unmerging.

The win forms tool strip control has no provision for automatic unmerging of child form tool strip controls from the MDI Parent form tool strip; If anybody knows why the folks in Redmond did this please let me know. Anyway, to work around this you need to use the ToolStripManagers RevertMerge method. Sounds simple, right?

Well... yes and no.

The answer lies in using OnMdiChildActivate method this fires the MdiChildActivate Event. If you try using MdiChildActivate by itself nothing happens by the way. so you need this method to fire it.

First you will need a MDI parent form with a tool strip and a MDI Child form with a tool strip. Name the tool strips tsParent and tsChild. Set the tsChilds visible property to false. Add controls to the tool strips as needed.

Next add an Interface to you solution and call it IChildForm. For our purposes this interface will have only one property called ChildToolStrip


namespace foo
{

interface IChildForm
{
ToolStrip ChildToolStrip { get;set;}
}
}

Next you need to implement this interface in the Child Form(s).

public ToolStrip ChildToolStrip
{
get
{
return tsChild;
}
set
{
tsChild = value;
}
}


Next...You will need to override OnMdiChildAcivate in the parent form. Also don't forget to call the base implementation
of OnMdiChidActivate().

protected override void OnMdiChildActivate(EventArgs e)
{

base.OnMdiChildActivate(e); //REQUIRED
HandleChildMerge(); //Handle merging

}

Next you will need to call the base implementation of OnMdiChildActivate. Next add the following code for the HandleChildMerge method.

private void HandleChildMerge()
{
ToolStripManager.RevertMerge(tsParent);
IChildForm ChildForm = ActiveMdiChild as IChildForm;
if (ChildForm != null)
{
ToolStripManager.Merge(ChildForm.ChildToolStrip, tsParent);
}
}

Now your toolstrips should unmerge automatically...

No comments: