Writing It by Hand

While wizards and property windows make creating toolbars easy, they do limit you in some interesting, if subtle ways. In the previous code, you set the Button's Tag property to a string (e.g., "New"), and in the event handler, you switched on that string:

image with no caption

private void toolBar1_ButtonClick(
   object sender, 
   System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
   switch ( e.Button.Tag.ToString(  ) )
   {
      case "New":
         mnuNew.PerformClick(  );
         break;
      case "Open":
         mnuFileOpen.PerformClick(  );
            break;
      case "Save":
         mnuFileSave.PerformClick(  );
         break;
   }
   
}

A tag, however, can be any type of object. It would be nice to put a reference to the MenuItem itself into the tag; this would greatly simplify the event handler:

image with no caption

private void toolBar1_ButtonClick(
   object sender, 
   System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
   ToolBarButton btn = e.Button;
   MenuItem mi = (MenuItem) btn.Tag;
   mi.PerformClick(  );
}

Creating the toolbar by hand is not much more difficult than creating it with Visual Studio .NET, as illustrated in Example 18-7 in C# and in Example 18-8 in VB.NET. In these examples, the modified code from the previous examples is highlighted. An analysis follows the code listings.

Example 18-7. Creating toolbars by hand in C# (ToolBarsByHandCS)

using System; using System.Drawing; ...

Get Programming .NET Windows Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.