Command Bar Buttons

As noted, every CommandBar control contains three buttons by default: OK, Close, and Help. Each default button has a property that determines whether the button is displayed; however, a Close button is always displayed if an OK button or Help button is displayed. Each button also has an associated event that is raised when a user chooses the button. You cannot change the style of the default buttons.

The following table shows the properties and events of the default buttons.

Button
Property
Event
OK OKButton OKClick
Help HelpButton HelpClick
Close CloseButton The application closes.

The CommandBarButton is a button object you can place on a CommandBar control. A CommandBarButton can serve as a check box, option button, or standard command button. A CommandBarButton also can act as a separator to define an option button group.

The following code example shows how to add a button to a CommandBar.

Dim B As CommandBarButton
Set B = CommandBar1.Controls.Add(cbrButton)

Once you add the button, you can change it to one of several styles by setting the Style property. These styles include cbrAutoSize, cbrButtonGroup, cbrDefault, cbrCheck, cbrDefault, and cbrSeparator.

The following code example shows how to change the style of a CommandBarButton to a check-box style. The control does not resemble a check box in appearance, but like a check box it can appear as though it is pressed in. The following code example shows how to set the Value property to 1 for a pressed state:

B.Style = cbrCheckbox
B.Value = 1

As an option, you can change a button’s appearance by changing the MixedState property, which shades a control when set to True.

In addition, the CommandBar control supports using an ImageList to put an image on a CommandBarButton. You can add a row of buttons to a control, then set the images to create a set of controls that looks and acts like a toolbar. The following code example shows how to set the image of a CommandBarButton.

B.Image = 1
CommandBar1.ImageList = ImageList1.hImageList

Once you place buttons on the CommandBar, you can receive event notifications. The following code example shows the syntax for the button event.

Private Sub commandbar_ButtonClick(ByVal Button As CommandBarButton)

Because the ButtonClick event passes the button by value, you cannot make changes directly to the CommandBarButton object. Instead, you must use the Key property to identify the button in the CommandBarControls collection, then change the properties of the corresponding member of the collection.

The following code example shows how to set the Key property of a CommandBarButton and use it to identify a button chosen by a user.

Dim B as CommandBarButton
Set B = CommandBar1.Controls.Add(cbrButton,"ButtonOne")
. . .
Private Sub CommandBar1_ButtonClick(ByVal Button As CommandBarButton)
  If Button.Key = "ButtonOne" Then MsgBox "It was button 'B' "
End Sub