Share via


Creating a Command Bar Control

In some cases, you might want to provide access to your add-in through a menu command.

To create a command bar control that displays the add-in's form

  1. In the add-in designer's module, use the WithEvents keyword to declare a module-level variable of type CommandBarButton. This creates an event-ready CommandBarButton object.

  2. In the same module, create the Click event procedure template for the CommandBarButton object by clicking the name of the object variable in the Object box and then clicking Click in the Procedure dialog box.

  3. Write code within the event-procedure template to open the form when the Click event occurs.

  4. In the OnConnection event procedure, check to see whether the command bar control already exists, and return a reference to it if it does. If it does not exist, create the new command bar control, and return a reference to it. You must check whether the command bar control exists, so you do not create a new control each time your code runs.

  5. When you create the new command bar control, set the Tag property for the CommandBarButton object to a unique string. This is necessary only for COM add-ins running in Microsoft® Word, but it is recommended for COM add-ins running in any host application.

  6. When you create the new command bar control, set the OnAction property for the command bar control if the COM add-in is to be demand-loaded. If you fail to set the OnAction property, the command bar button will load the add-in the first time the application starts, but it will not load the add-in when the application is closed and reopened.

  7. Within the OnConnection event procedure, assign the reference to the command bar control to the event-ready CommandBarButton object variable.

  8. Add code to the OnDisconnection event to remove the command bar control when the add-in is unloaded.

    Note   The add-in designer in the COM add-in template project includes code that performs all these steps to create a menu item on the Tools menu. By default, the template project has a reference set to the Microsoft® Office XP object library, so you can work with Office command bars.

See Also

Hooking a COM Add-in Up to a Command Bar Control