Using CommandBar Objects to Customize the Visio User Interface

3 4

Microsoft Visio and other Microsoft Office applications share the same technology for creating menus and toolbars, and this technology is available to you through the Microsoft Office command bars object model. The command bars object model exposes a wealth of objects, collections, properties, and methods that you can use to show, hide, and modify existing command bars and command bar controls, and create new ones. In addition, you can specify a Microsoft Visual Basic for Applications (VBA) procedure to run when a user clicks a command bar button or to respond to events triggered by a command bar or command bar control.

Because the command bars object model is shared by Visio and all Office applications, you can write code to manipulate command bars that can be used in any custom Office application or Visio solution you develop. Everything the user can do in Visio using the Customize dialog box, you can also do in your solution code using the Office command bars object model.

Note


The topics in this section provide information on the basics of working with command bars in Visio. For other details about working with command bars, see "Working with Command Bars" in the Microsoft Office XP Developer's Guide.For details about the CommandBars collection and CommandBar and CommandBarControl objects, and their associated properties, methods, and events, see the Microsoft Office Visual Basic Reference, Microsoft Press, 2001.

Working with the Command Bars Object Model

Beginning with Microsoft Visio 2002, you can use Microsoft Office CommandBar objects to customize the Visio user interface. In Visio and Office applications, there are three kinds of CommandBar objects: toolbars, menu bars, and pop-up menus. Pop-up menus are displayed in three ways: as menus that drop down from menu bars, as submenus that cascade off menu commands, and as shortcut menus. Shortcut menus (also called "right-click menus") are menus that appear when you right-click an element in the application.

Note


Changes you make to the Visio user interface using Visio UIObject objects are still fully supported in Visio 2002. However, the Microsoft Office command bars object model offers a robust and viable alternative for customizing the Visio user interface for your solutions.

The command bars object model is straightforward to learn and to program with, and you can easily reuse your code in any Office solution. It also supports the creation of custom text boxes, combo boxes, and drop-down list boxes—objects that aren't supported in the Visio object model.

You work with the following collections and objects in the command bars object model: the CommandBars and CommandBarControls collections, and the CommandBar, CommandBarButton, CommandBarComboBox, CommandBarControl, and CommandBarPopup objects.

There are several differences between working with CommandBar objects and Visio UIObject objects:

  • Unlike Visio UIObject objects, where menus and toolbars are separated into two groups containing different types of objects (menus and menu items, and toolbars and toolbar items), CommandBar objects are grouped into a single CommandBars collection, in which menus and toolbars are treated as the same kind of object. Similarly, menu items and toolbar items are treated as CommandBarControl objects.
  • Changes that you make to the Visio user interface using CommandBar objects are made at the application level, not at the document level. And, unless you flag specific changes as temporary, the changes you make to the user interface persist between application sessions. Changes that you make to the Visio user interface using UIObject objects can be made at the application or document level, and these changes do not persist between application sessions.
  • Changes you make to the Visio user interface using CommandBar objects are applied immediately to whatever command bars are currently active. If you use Visio UIObject objects to change the user interface, you typically start with a snapshot of the user interface, make your changes to that snapshot, and then apply the entire snapshot to the current user interface in one operation.

Note


To access CommandBar objects in Microsoft Visual Basic for Applications (VBA) or Microsoft Visual Basic, you must set a reference to the Microsoft Office 10.0 object library.

Creating a Command Bar

You create a command bar by using the CommandBars collection's Add method. The Add method creates a toolbar by default. To create a menu bar or pop-up menu instead, use the msoBarMenuBar or msoBarPopup constant in the Add method's Position argument.

You can create toolbars by using the Customize dialog box in Visio, or by accessing the Microsoft Office command bars object model. However, to create menu bars or pop-up menus, you must use CommandBar and CommandBarControl objects.

The following code sample illustrates how to create all three types of CommandBar objects:

 Dim cbrCmdBar As CommandBar 'Create a toolbar. Set cbrCmdBar = Application.CommandBars.Add(Name:= "MyNewToolbar") 'Create temporary toolbar that doesn't 'persist between application sessions. Set cbrCmdBar = Application.CommandBars.Add(Name:= _       "MyNewToolbar",Temporary:=True) 'Create a menu bar. Set cbrCmdBar = Application.CommandBars.Add(Name:= "MyNewMenuBar", _       Position:=msoBarMenuBar) 'Create a pop-up menu. Set cbrCmdBar = Application.CommandBars.Add(Name:= _       "MyNewPopupMenu", Position:=msoBarPopup) 

After you have created a command bar, you can then add any controls that you want.

Note


To access CommandBar objects in VBA or Visual Basic, you must set a reference to the Microsoft Office 10.0 object library.

Specifying the context for displaying a command bar

The Visio object model partitions each collection of toolbars and menus into separate context sets, of which only one context can be active and visible at a given time (depending on what the user is doing and what window is currently active in Visio). Visio switches contexts frequently, such as whenever a new drawing opens or a user switches between open drawings.

Visio manages the display of command bars when switching between contexts. For example, if you define the context for a custom command bar to be the ShapeSheet window (visUIObjSetShapesheet), Visio automatically enables the command bar when the ShapeSheet context is active, and automatically disables the command bar when Visio switches to a different context such as the drawing window (visUIObjSetDrawing) or the Print Preview window (visUIObjSetPrintPreview).

Because Visio has multiple contexts, you need to define the context in which your command bar is available in Visio. You assign the context in which you want a command bar to appear using the Context property of the CommandBar object.

The Context property setting indicates the context that the command bar appears in and whether the command bar is visible or hidden when the context becomes active. The context number is a String value (for example visUIObjSetDrawing or "2" ), which is followed by an asterisk if the command bar should be visible in that context while the context is active (for example, visUIObjSetShapeSheet & "*" or "4*" ). For example, the Standard toolbar in the drawing window context typically returns a value of "2*" , whereas the Action toolbar typically returns a value of "2" .

Note


The default value for any new command bar that you create is visUIObjSetDrawing or "2" , which means that the command bar is hidden when the drawing window context becomes active.

The following are valid context settings for the Context property:

  • visUIObjSetDrawing (2)
  • visUIObjSetStencil (3)
  • visUIObjSetShapeSheet (4)
  • visUIObjSetIcon (5)
  • visUIObjSetPrintPreview (7)

Attempting to set the Context property to any other value will fail. You can change the visibility for any command bar. However, you can only change the context number for custom command bars (not built-in command bars).

The following code samples demonstrate settings for the Context property of a command bar:

 'Set the command bar to be enabled and visible 'when the drawing window context is active. cbar.Context = Str(visUIObjSetDrawing) & "*" 'Set the command bar to be hidden (but enabled) 'when the ShapeSheet window context is active. cbar.Context = visUIObjSetShapeSheet 

Displaying a command bar

The best way to display a command bar in Visio is to use the CommandBar object's Context property. This approach allows you to reliably set the visibility of command bars in any context, regardless of what context is currently active in Visio.

You specify that a command bar is visible when the context becomes active by including an asterisk when you set the property, or specify that the command bar is hidden when the context becomes active by omitting the asterisk. For details on using the Context property, see Specifying the context for displaying a command bar earlier in this section.

Another way to show or hide a command bar is to use the CommandBar object's Visible property. However, you can only set this property for command bars that are in the current context, and therefore enabled. When using the Visible property, you should first determine if a command bar is enabled by querying the Enabled property of a CommandBar object.

For example:

 'Display the command bar in the current context. 'Check the Enabled property before 'attempting to set the Visible property. If cbar.Enabled = True Then       cbar.Visible = True End If 'Hide the command bar in the current context. 'Check the Enabled property before 'attempting to set the Visible property. If cbar.Enabled = True Then       cbar.Visible = False End If 

Note


Setting the Visible property of a command bar that is not in the current context results in an error.

Maintaining references to command bar controls when contexts change

Every time the context changes, Visio removes and then reapplies all custom user interface changes. To maintain references to command bar controls, you must assign a unique tag to each control using the Tag property. For example:

 Public Sub Form_Load()       With Application.CommandBars.Add"MyBar")             With myBar.Controls.Add(msoControlButton)                   .Tag = "MyBar.MyControl"             End With       End With End Sub 

You also need to assign a unique tag to a command bar control if you will be using the FindControl method in your code, for example:

 Public Sub DoSomething()       Dim myControl As Office.CommandBar       Set myControl = Application.CommandBars("MyBar"). _             FindControl(Tag := "MyBar.MyControl")       'Do stuff with myControl. End Sub 

The Microsoft Office dynamic-link library (MSO.dll) automatically hooks back into event handlers for command bar controls, provided the controls use the Tag property. The following code will continue to work after the context changes:

 Private WithEvents myButton As Office.CommandBarButton Public Sub Form_Load()       With Application.CommandBars.Add("MyBar")             Set myButton = .Controls.Add(msoControlButton)             myButton.Tag = "MyBar.MyControl"       End With End Sub Private Sub myButton_Click(ByVal Ctrl As Office.CommandBarButton, _       CancelDefault As Boolean)       'The button was pushed. End Sub 

Note


To access the Tag property and FindControl method of a CommandBar object in VBA or Visual Basic, you must set a reference to the Microsoft Office 10.0 object library.

Getting Information about Command Bars

The CommandBars property of the Visio Application object returns a reference to the CommandBars collection that represents the command bars in the container application.

The following code demonstrates using the CommandBars property to list the command bars in the current application:

 Public Sub IterateCommandBars()       Dim myCommandBars As CommandBars       Dim myCommandBar As CommandBar       'Get the set of CommandBars       'for the application.       Set myCommandBars = Application.CommandBars       'List each CommandBar in       'the Immediate window.       For Each myCommandBar In myCommandBars             Debug.Print myCommandBar.Name       Next End Sub 

Deleting a Command Bar

Use the Delete method of the CommandBars collection to remove an existing command bar from the collection. You can delete toolbars and menu bars using the Customize dialog box in Visio or by using code. However, you can delete pop-up menus only by using code.

The following procedure illustrates one way to delete a CommandBar object:

 Sub DeleteDrawingCommandBar() Dim cbars As CommandBars       Dim cbar1 As CommandBar On Error Resume Next       'The gateway to the Microsoft Office command bars object model       Set cbars = Application.CommandBars       'Get the command bar named MyDrawingCommandBar       'added by AddDrawingContextCommandBar().       Set cbar1 = cbars("MyDrawingCommandBar")       'Delete that command bar.       cbar1.Delete End Sub 

An error occurs if the command bar does not exist. The procedure uses the On Error Resume Next statement to ignore this error because, if an error occurs, it means there is nothing to delete. An error also occurs if you try to delete a built-in command bar, such as the Standard toolbar, which cannot be deleted.

Working with Command Bar Controls

Each CommandBar object has a CommandBarControls collection, which contains all the controls (CommandBarControl objects) on the command bar. You use the Controls property of a CommandBar object to refer to a control on a command bar. If the control is of the type msoControlPopup, it also will have a CommandBarControls collection representing each control on the pop-up menu. (Pop-up menu controls represent menus and submenus and can be nested several layers deep.)

In this example, the code returns a reference to the New button on the Standard toolbar:

 Dim ctlCBarControl As CommandBarControl Set ctlCBarControl = _       Application.CommandBars("Standard").Controls("New") 

When you have a reference to a control on a command bar, you can access all available properties and methods of that control.

Note


When you refer to a command bar control by using the control's Caption property, you must be sure to specify the caption exactly as it appears on the menu. A more reliable way to identify specific controls is to use the Tag property. By using the Tag property, you don't need to worry about users renaming control captions, and it's easier to port your solution to different language versions.

Adding controls to a command bar

To add a control to a command bar, use the Add method of the CommandBarControls collection that specifies the type of control you want to create. You can add the following types of controls:

  • Button (msoControlButton)
  • Text box (msoControlEdit)
  • Drop-down list box (msoControlDropdown)
  • Combo box (msoControlComboBox)
  • Pop-up menu (msoControlPopup)

The following example adds a button control to a command bar:

 'Add a button to MyDrawingCommandBar 'that runs a VBA macro. Set cbButton = cbar.Controls.Add(Type:=msoControlButton) With cbButton       .Caption = "VBA Macro"       .TooltipText = "Click this button to run a VBA Macro"       'Use the Tag property for context switching and       'for use with the FindControl method.       .Tag = "cbbVBAMacro"       'Set the button face to use an internal icon.       .FaceID = 7075       'Use the OnAction property to run a VBA macro       'contained in this document.       .OnAction = "ThisDocument.HelloWorld" End With 

Using the OnAction property of a CommandBarControl object

Each CommandBarControl object in a CommandBarControls collection has an OnAction property, which specifies a procedure to run when a user clicks a button, displays a menu, or changes the contents of a combo box control.

In Visio, you can use the OnAction property to load a Component Object Model (COM) add-in, or to run a VBA macro, or a Visio add-on VSL (Visio library) in response to a user clicking a toolbar or menu item. (You do not need to write a handler for the Click event when you use the OnAction property.)

Use the following syntax to set the OnAction property to run a VBA macro or Visio add-on:

 ctlButton.OnAction = "<ProjectName>!<MacroName>" 
 ctlButton.OnAction = "<MacroName|AddonName>" 

For a COM add-in, the syntax for setting the OnAction property is:

 ctlButton.OnAction = "!<ProgID>" 

where ctlButton is the CommandBarButton object and ProgID is the programmatic identifier for the add-in. The programmatic identifier is the subkey that is created for the add-in in the Windows registry. You must set the OnAction property for any COM add-in you create that is loaded on demand. For details on implementing COM add-ins, see Chapter 23, Using COM Add-ins in a Visio Solution.

The following code demonstrates the various syntax options for the OnAction property:

 'Runs a COM add-in that is registered for Visio. MyCtlButton.OnAction = "!<MyAddin.VisioCOMAddin>" 'Runs the Hello World macro in the ThisDocument module 'of the Drawing1 project. Drawing1.vsd must be open. MyCtlButton.OnAction = "Drawing1!ThisDocument.HelloWorld" 'Runs the Hello World macro in the active document. MyCtlButton.OnAction = "ThisDocument.HelloWorld" 'Runs a Visio add-on named "My Organization Chart". 'Visio automatically looks at the Parameter property 'of the control to determine add-on arguments, if any. MyCtlButton.OnAction = "My Organization Chart" MyCtlButton.Parameter = "/FILENAME ""C:\Samples\My Organization Chart Data.xls""" 

The following code sets a button control's OnAction property to run a Visio add-on named "Hello World".

 'Add a button to the command bar. Set cbButton = cbar.Controls.Add(Type:=msoControlButton) With cbButton       .Caption = "Run Hello World add-on"       .OnAction = "Hello World" End With 

Note


To use the OnAction property in VBA or Visual Basic, you must set a reference to the Microsoft Office 10.0 object library.

You can also handle the Click event in response to a user clicking a command bar button. For details, see Using the Click event procedure of a command bar button later in this section.

Showing and enabling command bar controls

You specify whether a command bar control is shown on a command bar by using its Visible property. You specify whether a command bar control appears enabled or disabled (dimmed) by using its Enabled property. For example, the following two lines of code could be used to toggle the Visible and Enabled properties of the named controls:

 Application.CommandBars("Menu Bar").Controls("Edit").Enabled = False 
 Application.CommandBars("Formatting").Controls("Font").Visible = False 

Note


The Enabled and Visible properties differ in their behavior for custom controls versus built-in controls. For custom controls, True means always show or enable the control, and False means always hide or disable the control. For built-in controls, True means allow the command to determine the state of the control, and False means override the command's default behavior, thereby forcing the control to be hidden or disabled.

For details on using the State property of a control to toggle its checked or pressed state to represent a particular condition in the application, see "Visually Indicating the State of a Command Bar Control" in the Microsoft Office XP Developer's Guide.

Working with images on command bar buttons

Every built-in command bar button has an image associated with it. You can use these images on your own command bar buttons as long as you know the FaceId property value of the built-in button that contains the image. The values for the FaceId property range from zero (no image) to the total number of Microsoft Office button images (of which there are several thousand).

The following code sets a CommandBarButton object's FaceId property to a Visio macro icon:

 'Add a button that runs a VBA macro 'to a command bar. Set cbButton = cbar.Controls.Add(Type:=msoControlButton) With cbButton       .Caption = "VBA Macro"       .TooltipText = "Click this button to run a VBA Macro"       'Set the button face to use an internal icon.       .FaceID = 7075 End With 

To add a bitmap for the button face rather than using a built-in button image, set the Picture property of a CommandBarButton object. For more details, see the Microsoft Office Visual Basic Reference.

Writing Code for a Command Bar: an Example

The following example shows code for the ThisDocument object and a class module named CommandBarEventHandler that creates a command bar with three buttons. The example demonstrates how you might create and display a command bar with buttons, set various relevant properties such as the Context and Position properties of the command bar, and properties for button controls such as Caption, TooltipText, Tag, FaceId, and OnAction. It also includes code for handling the Click event of a button control and for deleting a command bar.

This is the code for ThisDocument:

 'Event handling class for CommandBarButtonClick events Public myEventClass As New CommandBarEventHandler 'Adds a command bar that is available 'when a drawing window is active. Sub AddDrawingContextCommandBar() Dim cbars As Office.CommandBars       Dim cbar As Office.CommandBar       Dim cbButton As Office.CommandBarButton       'The gateway to the Microsoft Office command bars object model       'is the CommandBars property of the Visio Application object.       Set cbars = Application.CommandBars       'Add a new command bar named MyDrawingCommandBar.       'that only lasts through the current Visio       'application session.       Set cbar = cbars.Add(Name:="MyDrawingCommandBar", _             Position:=msoBarTop, Temporary:=True)       'Prevent users from modifying       'the custom command bar.       cbar.Protection = msoBarNoCustomize       'Set the appropriate context and visibility       'for the custom command bar.       '* = visible in given context.       cbar.Context = Str(visUIObjSetDrawing) & "*"       'Add a button to MyDrawingCommandBar       'that runs a VBA macro.       Set cbButton = cbar.Controls.Add(Type:=msoControlButton)       With cbButton             .Caption = "VBA Macro"             .TooltipText = "Click this button to run a VBA Macro"             'Use the Tag property for context switching and             'for use with the FindControl method.             .Tag = "cbbVBAMacro"             'Set the button face to use an internal icon.             .FaceID = 7075             'Use the OnAction property to run a VBA macro             'contained in this document.             .OnAction = "ThisDocument.HelloWorld"       End With       'Release this object.       Set cbButton = Nothing       'Add another button to MyDrawingCommandBar       'that loads a COM add-in.       Set cbButton = cbar.Controls.Add(Type:=msoControlButton)       With cbButton             .Caption = "Run COM add-in"             .TooltipText = "Click this button to run a COM add-in"             'Use the Tag property for context switching and             'for use with the FindControl method.             .Tag = "cbbCOMAddin"             'Set the button face to use an internal icon.             .FaceID = 7075             'Use the OnAction property to load a COM add-in.             .OnAction = "!<MyAddin.VisioCOMAddin>"       End With Set cbButton = Nothing       'Add another button to MyDrawingCommandBar       'that will be monitored by the event handling       'class for the Click event. Note that no OnAction       'property is used here.       Set cbButton = cbar.Controls.Add(Type:=msoControlButton)       With cbButton             .Caption = "ClickEvent"             .TooltipText = "Click this button to trigger event"             'Use the Tag property for context switching and             'for use with the FindControl method.             .Tag = "cbbClickEvent"             'Set the button face to use an internal icon.             .FaceID = 7075       End With       'Set a reference to the command bar button       'in the event handling class.       Set myEventClass.cbbMyButton = cbButton End Sub Private Sub HelloWorld()       MsgBox "Hello World!" End Sub Sub DeleteDrawingCommandBar() Dim cbars As Office.CommandBars       Dim cbar1 As Office.CommandBar On Error Resume Next       'The gateway to the Microsoft Office command bars object model       Set cbars = Application.CommandBars       'Get the command bar named MyDrawingCommandBar       'added by AddDrawingContextCommandBar().       Set cbar1 = cbars("MyDrawingCommandBar")       'Delete that command bar.       cbar1.Delete End Sub 

Following is the code for a class module named CommandBarEventHandler:

 'This class can handle the Click event 'of one command bar button. 'Use the code to create an instance of this class  'and set a reference to the cbbMyButton object. 'Note the use of the WithEvents keyword. Public WithEvents cbbMyButton As CommandBarButton Private Sub cbbMyButton_Click(ByVal Ctrl As Office.CommandBarButton, _       CancelDefault As Boolean)       'Put event handling code here to handle       'a click of the referenced command bar button. MsgBox "Button " & Ctrl.Caption & " was clicked." End Sub 

Using the Click event procedure of a command bar button

You can use command bar event procedures to run your own code in response to an event. In addition, you can use these event procedures to substitute your own code for the default behavior of a built-in control. For example, the CommandBarButton object exposes a Click event procedure that you can use to run code in response to an event:

 'This class can handle the Click event 'of one command bar button.  'Use the code to create an instance of this class  'and set a reference to the cbbMyButton object. Public WithEvents cbbMyButton As CommandBarButton Private Sub cbbMyButton_Click(ByVal Ctrl As Office.CommandBarButton, _       CancelDefault As Boolean)       'Put event handling code here to handle       'a click of the referenced command bar button. MsgBox "Button " & Ctrl.Caption & " was clicked." End Sub 

Note


For details on working with other events in the command bars object model, see "Working with Command Bar Events" in the Microsoft Office XP Developer's Guide, Microsoft Press, 2001.

Preventing Users from Modifying Custom Command Bars

To prevent users from changing your custom user interface—but allow them to perform normal customization of the built-in user interface—set the Protection property of the custom CommandBar object to msoBarNoCustomize.

 Application.CommandBars("My CommandBar").Protection = _       msoBarNoCustomize 

Preventing Users from Modifying All Visio Command Bars

To prevent users from changing any built-in or custom command bar in Visio through the Visio user interface, set the DisableCustomize property of the CommandBars collection to True. For example:

 'Prevents user's from customizing 'command bars through the user interface. Application.CommandBars.DisableCustomize = True 

Note


Be aware that setting the DisableCustomize property to True will prevent users from using the Visio user interface to modify all Visio menus or toolbars, including the custom command bars that you've created for a particular solution. However, you will still be able make changes to the user interface programmatically.

This property setting does not persist between Visio application sessions, so you will need to set it and restore it for each Visio application session.



Developing Microsoft Visio Solutions 2001
Developing Microsoft Visio Solutions (Pro-Documentation)
ISBN: 0735613532
EAN: 2147483647
Year: 2004
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net