How to: Add or Remove a Menu Item on a Context Menu

Outlook Developer Reference

The following context menu events provide a reference to the CommandBar object that represents the context menu to be displayed:

You can use the Add method of the Controls collection for the CommandBar object to add command bar controls to the context menu. Each command bar control also supplies a Delete method to remove the control from the parent object. Command bar controls can be added either directly to the CommandBar object or to a CommandBarPopup object, so that your add-in can create submenus.

Bb206753.vs_note(en-us,office.12).gif  Note
If you want to prevent the display of menu items provided by Outlook, you should hide, rather than remove, such menu items by setting the Visible property for menu items to be hidden to False. For more information about hiding or disabling menu items, see How to: Hide or Disable a Menu Item on a Context Menu.

This sample provides an event handler that, each time the ItemContextMenuDisplay event occurs, adds a new menu item to the bottom of the selection context menu which displays the number of times the context menu has been displayed. The sample performs the following actions:

  1. The sample first resets intCounter, a static Integer variable that represents the number of times that the ItemContextMenuDisplay event has occurred, if the variable has not yet been set or if the value of the variable is greater than 100. If the variable is already initialized and its value is less than 100, the sample increments the value of the variable by 1.

  2. It then creates a CommandBarButton object in the Controls collection of the CommandBar object, adding a single menu item to the bottom of the context menu.

  3. Finally, the sample then configures the CommandBarButton:

    • The Caption property is set so that the title of the menu item displays the contents of the intCounter variable.
    • The Enabled property is set to False, so that the menu item is disabled within the context menu.
    • The BeginGroup property is set to True, so that the menu item is displayed within a separate group in the context menu.
  Private Sub Application_ItemContextMenuDisplay( _
    ByVal CommandBar As Office.CommandBar, _
    ByVal Selection As Selection)
    
    Static intCounter As Integer
    
    On Error GoTo ErrRoutine
    
    ' Increment or reset the counter
    If intCounter < 1 Or intCounter > 100 Then
        intCounter = 1
    Else
        intCounter = intCounter + 1
    End If
    
    ' Add the menu.
    Set objMenu = CommandBar.Controls.Add(msoControlButton)
    objMenu.Caption = "Displayed " & intCounter & " times"
    objMenu.Enabled = False
    objMenu.BeginGroup = True
    
EndRoutine:
    On Error GoTo 0
    Exit Sub

ErrRoutine: MsgBox Err.Number & " - " & Err.Description, _ vbOKOnly Or vbCritical, _ "Application_ItemContextMenuDisplay"

GoTo EndRoutine

End Sub