Adding Toolbars

Adding Toolbars

Toolbars are an effective middle ground between using shortcut keys and plowing through menus to execute the desired command. Because they allow easy point-and-click access to the most frequently used features of your application, toolbars are considered a must by users.

In the following subsections, you’ll learn how to create toolbars and format them to achieve the visual appearance you want. You’ll also find a description of the various button styles you include in your toolbars to make users more productive.

Creating a Toolbar

The easiest way to add a toolbar to your application or form is to design the toolbar using the Microsoft Visual C# .NET Forms Designer. You first need to add two controls to your form: an ImageList control and the ToolBar control itself. When you drag the ToolBar control onto your form, it will automatically dock at the top of your form; the ImageList control is an invisible control that sits below the form.

You next need to add images to the ImageList control; these images will appear on the toolbar buttons. Visual Studio .NET includes images for toolbars—one set to match the Microsoft Office toolbar and one set to match Microsoft Windows 95. For this example, we’ll use the Office-style bitmaps, which can be found in \Program Files\Microsoft Visual Studio .NET\Common7\Graphics\ bitmaps\OffCtlBr\Small\Color. The bitmaps aren’t stellar, but they’ll get you off to a good start.

The example toolbar we’re building is based on standard actions you’ll find in almost any application: New, Open, Save, Cut, Copy, Paste, and Help. Each of these commands is represented by a single image file. You can use the Image Collection Editor to add and remove images to the control. To access it, click the ellipsis button next to the Images property in the Properties window of the ImageList control. The completed Image Collection Editor is shown in Figure 17-1.

With the images all defined, the final step is to create the buttons on the toolbar. To accomplish this, select Buttons in the Properties window for the ToolBar control to open the ToolBarButton Collection Editor. For every button, add one ToolBarButton object, as shown in Figure 17-2. You can use the Add and Remove buttons to add buttons to and remove buttons from the ToolBar control. To configure the properties for each button, use the pane on the right side of the editor.

Figure 17-1.
Adding bitmaps to the ImageList control with the Image Collection Editor.
Figure 17-2.
Defining buttons for the toolbar.

All properties that have been changed are displayed in boldface in this window. In this case, the properties that have been set are Name (the name of the ToolBarButton button), ImageIndex (the bitmap that will be used), Text (the text string displayed on the button), and ToolTipText (the text that will appear on mouseover).

After you’ve defined all your buttons, you can view the completed toolbar in the Forms Designer. (We’ll return to the subject of separators later in this chapter, in the section “Defining Toolbar Button Styles”.) One final thing remains to be done: wire up an event handler to the toolbar so that we know which button was pressed. To do this, create a ButtonClick event handler and add the following code:

private void OnButtonClick(object sender, 
    System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
    ToolBarButton tbCurrent = e.Button;
    MessageBox.Show("You clicked button " + tbCurrent.Text);
}

The ToolBarButtonClickEventArgs class is simple to use because it includes only one property: Button. This property enables us to retrieve the instance of ToolBarButton that was clicked. This example uses the Text property to display a simple message box; your applications will likely respond with much more sophisticated actions.

Modifying the Toolbar’s Appearance

A toolbar doesn’t come in just one flavor—you can adapt it visually to suit your application’s needs, or you can let your users decide at run time how they want the toolbar to appear. Table 17-1 lists the properties that influence how your toolbar is displayed.

Table 17-1.  ToolBar Properties for Visual Style 

Property

Description

Appearance

Specifies how the toolbar is displayed. Allowed values are defined in the ToolBarAppearance enumeration. The default is Normal.

BorderStyle

Specifies the border style of the toolbar. Allowed values are defined in the BorderStyle enumeration. The default is None.

Divider

Specifies whether to display a divider between the toolbar and the menu bar. The default is true.

TextAlign

Specifies the alignment for text on toolbar buttons. Allowed values are defined in the ToolBarTextAlign enumeration. The default is Underneath.

Wrappable

Specifies whether toolbar buttons can wrap to another line if the toolbar is too small to display all the buttons on the same line. The default is true.

note

Refer to the Platform SDK for a detailed discussion about the enumerations mentioned in Table 17-1.

The sample application ToolbarStyles, on the companion CD, was designed to let you experiment with visual changes to the toolbar. The application loads the ImageList and ToolBar controls dynamically in the constructor, after the call to InitializeComponent, as shown here:

// Initialize the ImageList object.
tbMain.ImageList = new ImageList();
Bitmap bmpImageStrip = new Bitmap(GetType(), "Toolbar.bmp");
bmpImageStrip.MakeTransparent(Color.FromArgb(0xff, 0x00, 0xff));
tbMain.ImageList.ImageSize = new Size(16, 15);
tbMain.ImageList.Images.AddStrip(bmpImageStrip);

// Create the toolbar buttons.
for (int i=0; i < astrTBarButtons.Length; i++)
{
    ToolBarButton tbb = new ToolBarButton();
    tbb.ImageIndex = i;
    tbb.ToolTipText = astrTBarButtons[i];
    tbMain.Buttons.Add(tbb);
}

The bitmap Toolbar.bmp is an embedded resource of the project. It sports a transparent background color, and the images aren’t the standard 16-by-16 pixels, but 16-by-15 instead. The reason for this deviation is that this bitmap was taken from an existing Microsoft Foundation Classes (MFC) Windows application project that included a toolbar—a conversion task that you might be facing too.

With the bitmap loaded into the ImageList control, we can start adding ToolBarButton objects to the ToolBar control. The astrTBarButtons array is defined as follows:

string[] astrTBarButtons = { "New", "Open", "Save",
                             "Cut", "Copy", "Paste", "Print", "Help"};

The text is used for the ToolTipText property, and the index in the array matches the bitmap index in the ImageList control, which is used for the ImageIndex property. With all buttons initialized, the application starts up, as shown in Figure 17-3.

Figure 17-3.
A standard toolbar with images only, no text, and a divider line between the menu bar and the toolbar.

On startup, the Divider property is automatically set to true and the Appearance property is set to Normal. To toggle the divider line, which is simply a line separating the toolbar and the menu bar, use the following code:

tbMain.Divider = !tbMain.Divider;

Another change that alters the look and feel of the toolbar considerably is switching from Normal to Flat appearance, as follows:

tbMain.Appearance = ToolBarAppearance.Flat;

The toolbar now looks like Figure 17-4.

To switch back to normal appearance, set the Appearance property to ToolBar­Appearance.Normal.

The example toolbar in the previous section displayed additional text beneath the image on the toolbar button. To achieve this effect at design time, you can use the Properties window to set the ToolBarButton object’s Text property to the text you want to display and then set the TextAlign property to the desired alignment—either centered underneath or displayed to the right of the bitmap.

Figure 17-4.
A flat toolbar with images only, no text, and a divider line between the menu bar and the toolbar.

You can also set these properties at run time. For example, the following code performs these tasks:

private void AddTextToToolBarButtons()
{
    for (int i=0; i < astrTBarButtons.Length; i++)
    {
        tbMain.Buttons[i].Text = astrTBarButtons[i];
    }
}

The AddTextToToolBarButtons method adds text to each ToolBarButton object contained in the Buttons collection. To display the text underneath the button image, you can set the TextAlign property to Underneath:

tbMain.TextAlign = ToolBarTextAlign.Underneath;

Your toolbar now looks like Figure 17-5.

Figure 17-5.
A flat toolbar with text underneath the button images and a divider line between the menu bar and the toolbar.

To display text to the right of the image, set the TextAlign property to Right. Your toolbar will resemble Figure 17-6.

Figure 17-6.
A flat toolbar with text to the right of the button images and a divider line between the menu bar and the toolbar.

So how do you revert to displaying images only at run time? The solution is to use the RemoveTextFromToolBarButtons method to remove all text from the ToolBarButton objects, as shown here:

private void RemoveTextFromToolBarButtons()
{
    for (int i=0; i < astrTBarButtons.Length; i++)
    {
        tbMain.Buttons[i].Text = "";
    }
    tbMain.Refresh();
}

The toolbar is now returned to normal, with no text displayed on the buttons.

Defining Toolbar Button Styles

You can also modify the appearance of the individual buttons on the toolbar. ToolBarButton objects come in four styles, with the push button style being the most familiar option. Table 17-2 lists the four styles available through the ToolBarButtonStyle enumeration.

The TBBStyle application, on the companion CD, demonstrates how each of these buttons works. This application sports a number of standard PushButton objects, two Separator objects to group the PushButton objects, one ToggleButton object that controls event handling, and one DropDownButton object that displays a shortcut menu. Figure 17-7 gives you an idea of how this application looks when executed.

Figure 17-7.
A toolbar that uses all four button styles.

For simplicity, the bitmaps for these buttons are added manually to the ImageList control. The toolbar properties are set programmatically with the use of these three arrays, as shown here:

string[] astrTBB = {"Cut", "Copy", "Paste", "", "Messages", "", "Help"};
ToolBarButtonStyle[] atbbStyles = {ToolBarButtonStyle.PushButton,
    ToolBarButtonStyle.PushButton, ToolBarButtonStyle.PushButton,
    ToolBarButtonStyle.Separator, ToolBarButtonStyle.ToggleButton,
    ToolBarButtonStyle.Separator, ToolBarButtonStyle.DropDownButton };
int[] anImageIndex = { 0, 1, 2, 0, 4, 0, 3 };

The first array defines the text for the ToolTip, with an empty string used for the separators. The second array holds the styles for each button, and the third array defines which image to use from the ImageList object. Armed with this information, the application can go about creating the toolbar, as shown in the code listing below.

for (int i=0; i < astrTBB.Length; i++)
{
    ToolBarButton tbb = new ToolBarButton();
    tbb.ImageIndex = anImageIndex[i];
    tbb.Style = atbbStyles[i];
    tbb.ToolTipText = astrTBB[i];
    if (tbb.Style == ToolBarButtonStyle.DropDownButton)
    {
        tbb.DropDownMenu = ddmDemo;
    }
    tbMain.Buttons.Add(tbb);
}

The drop-down arrow displays a demo shortcut menu, which is added to the form. When you click the arrow, the shortcut menu appears, as shown in Figure 17-8.

Figure 17-8.
Clicking a drop-down arrow to display a shortcut menu.

The button to the left of the drop-down button is a toggle button. It can be either pressed or released, and you can use it to display the states of your application. For example, you can use a toggle button to specify whether your toolbar will process button clicks, as shown here:

private void OnButtonClick(object sender, 
    System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
    bool bShowMessages = tbMain.Buttons[4].Pushed;
    if (true == bShowMessages)
    {
        MessageBox.Show("Button " + e.Button.ToolTipText + 
                        " was clicked");
    }
}

Toggle buttons have many practical uses. For example, you can use a toggle button to format text in boldface in a word processing application. As long as the button is depressed, all text is written in boldface. When the button is clicked again, the font returns to normal.



Part III: Programming Windows Forms