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:
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:
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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access