Build sample VSTO Outlook 2010, 2007, 2003 add-in / plugin,
customize toolbar, menu, ribbon in C#, VB.NET

Add-in Express™
for Microsoft® Office and VSTO

Add-in Express Home > Add-in Express for Office and VSTO > Online Guide > Building Outlook plugins in VSTO

Program VSTO Outlook add-ins / plug-ins

Add-in Express for VSTO is the first component set that applies the RAD paradigm to COM add-in development. Now you can build a VSTO Outlook 2010, Outlook 2007 and 2003 add-in / plugin faster than ever before. Add-in Express provides additional components for COM Add-ins in Outlook. For more information, please see:

Sample add-in for Outlook

Now let's see Add-in Express in action. The sample Outlook add-in project below is written in VB.NET, but you can use Visual C# and Delphi Prism as well. You can also download this sample Outlook add-in with source code

Step 1. Creating a new VSTO Outlook add-in project

If you use Visual Studio 2008, then close all opened solutions and select File | New | Project... in the menu and find the Add-in Express for VSTO Add-in item in the Extensibility node of the New Project dialog:

New Outlook add-in project

This starts the Add-in Express project wizard. In the project wizard window choose the programming language, the host application of your add-in and its version, make sure that the Generate the Setup Project option is on and click Finish.

If you use Visual Studio 2005 with VSTO 2005 SE installed, then create a new Outlook 2003 add-in solution and, in the Add New Item dialog, choose the Add-in Express Module item as shown on the screenshot below:

New Outlook add-in solution in Visual Studio 2005

This code of ThisAddin.vb (or ThisAddin.cs) will look like this:


Public Class ThisAddIn
    Private Sub ThisAddIn_Startup(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Me.Startup
        'Add-in Express for VSTO generated code
        ADXModule.Initialize(Me, System.Type.GetType("OutlookAddin1.ADXModule"))
    End Sub

    Private Sub ThisAddIn_Shutdown(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Me.Shutdown
        'Add-in Express for VSTO generated code
        ADXModule.Finalize(Me)
    End Sub
End Class
 

Step 2. Add-in module

The Add-in Express module (ADXModule.vb or ADXModule.cs) is the core part of your Outlook add-in project. In this module, you specify the add-in properties in the module's properties, add Add-in Express components to the module's designer, and write the functional code of your Outlook add-in.

Viewing source code of the Add-in Express module

To review its source code, in Solution Explorer, right-click the file and choose the View Code popup menu item. The VB.NET code of the module is as follows:


Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.Windows.Forms
Imports Outlook = Microsoft.Office.Interop.Outlook
Imports Office = Microsoft.Office.Core

<COMVISIBLE(TRUE)> _
Public Class ADXModule1
   Inherits AddinExpress.VSTO.ADXOutlookAddin

#Region " Component Designer generated code. "
   'Required by designer
   Private components As System.ComponentModel.IContainer

   'Required by designer - do not modify the following method
   Private Sub InitializeComponent()

   End Sub
#End Region

#Region " ADX automatic code "
   'Required by Add-in Express - do not modify
   'the methods within this region

   Public Overrides Function GetContainer() As _
      System.ComponentModel.IContainer
      If components Is Nothing Then
         components = New System.ComponentModel.Container
      End If
      GetContainer = components
   End Function

#End Region

   Public Sub New(ByVal Application As Object)
      MyBase.New(Application)
      'This call is required by the Component Designer
      InitializeComponent()
      'Add any initialization after the InitializeComponent() call
   End Sub

   Public Sub New()
      MyBase.New()
      'This call is required by the Component Designer
      InitializeComponent()
      'Add any initialization after the InitializeComponent() call
   End Sub

   Public ReadOnly Property OutlookApp() As Outlook._Application
      Get
         Return HostApplication
      End Get
   End Property
End Class

Partial Public Class ThisAddIn
   Protected Overrides Function RequestService(ByVal serviceGuid As Guid) _
      As Object
      If serviceGuid = GetType(Office.IRibbonExtensibility).GUID Then
         ADXModule1.Initialize(Me, _
            System.Type.GetType("OutlookAddIn1.ADXModule1"))
         Return ADXModule1.CurrentInstance
      End If
      Return MyBase.RequestService(serviceGuid)
   End Function
End Class

Step 3. Add-in Module designer

To access the Add-in Express Module Designer, in Solution Explorer, right-click the add-in module file and choose the View Designer popup menu item. The designer provides the add-in properties and a number of events including add-in events, application-level Outlook events, Ribbon control events, and Office 2010 and 2007 task pane related events. It is also a container for Add-in Express components that can be added to the module via the context menu of the designer.

In the Properties window for the add-in module designer, specify the name of your add-in, say My Outlook add-in.

Add-in Module designer

Step 4. Adding a new Outlook Explorer command bar

To add a command bar to Outlook Explorer windows, use the Add Explorer CommandBar command that adds an ADXOlExplorerCommandBar to the add-in module (see also Adding components to the Add-in Module).

Select the Explorer command bar component, then, in the Properties window, specify the command bar name in the CommandBarName property and specify its position in the Position property. The Explorer command bar component provides context-sensitive properties. They are FolderName, FolderNames, and ItemTypes.

Outlook Explorer commandbar component

In the screenshot above, you see an Outlook Explorer command bar component that creates a custom toolbar to be shown for every Outlook folder (FolderName = "*") the default item type of which is Mail.

Outlook Explorer command bar properties

In Outlook 2003, this command bar will be positioned at the top of the Outlook Explorer window. In Outlook 2007, this command bar will be shown in the Add-ins tab if the Visible property of the command bar is set to True and if the controls of the command bar are visible. See also Command bar: toolbar, menu and context menu and How To sample for Outlook explorer toolbars.

Step 5. Adding a new button onto the Outlook toolbar

To add a new button to the Outlook Explorer command bar, select the Explorer command bar component and, in the Properties window, choose the Controls property, and click the property editor button. This starts the command bar visual designer. In its UI, you can add / move /d elete any command bar control (see also Command Bar controls).

To add an icon to the button, add an ImageList to the add-in module. Then specify the button's Caption property and set the ImageList, Image, and ImageTransparentColor properties of the button. Finally, set the Style property because its default value doesn't show the button image (see the screenshot below).

Populating an Explorer commandbar with controls

Step 6. Customizing the Outlook 2010 and 2007 Ribbon User interface

To add a new tab to the Outlook Ribbon UI, you use the Add Ribbon Tab command that adds an ADXRibbonTab component to the module.

Office Ribbon tab component

In the Properties window, run the editor for the Controls collection of the Ribbon tab component. In the visual designer, use the toolbar buttons or context menu to add or delete Add-in Express components that form the Ribbon interface of your add-in. First, you add a Ribbon tab and change its caption to My Ribbon Tab. Then, you select the tab component, add a Ribbon group, and change its caption to My Ribbon Group. Next, you select the group, and add a button group. Finally, you select the button group and add a button. Set the button caption to My Ribbon Button. Use the ImageList, Image, and ImageTransparentColor properties to set the icon for the button.

Adding a custom button to the Outlook ribbon tab

Step 7. Adding a new Outlook Inspector command bar

Remember, the Ribbon Tab visual designer validates the Ribbon XML automatically, so from time to time you will run into the situation when you cannot add a control to some Ribbon level. It is a restriction of the Ribbon XML schema. Unlike other Ribbon-based applications, Outlook has numerous ribbons. Please use the Ribbons property of your ADXRibbonTab components to specify the ribbons you customize with your tabs. See also Office 2010 and 2007 Ribbon components.

Outlook Inspector command bar component

To add a command bar to Outlook Inspector windows, use the Add Inspector CommandBar command that adds an ADXOlInspectorCommandBar component to the Add-in Module.

The Inspector command bar component provides the same properties as the Explorer command bar component. However, if ItemTypes is Unknown and you specify the full path to a folder(s) in the FolderName (FolderNames) property of an inspector command bar component, the corresponding toolbar is displayed for inspectors that open Outlook items the Parent properties of which point to that folder. For more details about adding a new button onto the Inspector toolbar see Step 5 - Adding a new button to the Outlook toolbar. See also HowTo for Outlook inspector toolbars.

Step 8. Customizing Outlook main menu

In Outlook 2003 two main menu types are available for Outlook windows: Explorer and Inspector. Accordingly, Add-in Express provides two main menu components: Explorer Main Menu component and Inspector Main Menu component. You use the context menu of your Outlook add-in module to add them. Then you use the visual designer provided for the Controls property of the component.

For example, to add a custom control to the popup shown by the File | New item in all Outlook Explorer windows, you start our free Built-in Control Scanner to scan Outlook command bars and controls. The screenshot below shows the result of scanning. You need the Office IDs you see in the screenshot to bind Add-in Express controls to them:

Scanned Outlook command bar IDs

  • Add a popup control to the menu component and set its Id property to 30002
  • Add a popup control to the popup control above and set its Id to 30037
  • Add a button to the popup above and specify its properties.

The following screenshot shows the settings of the popup created at step 3 above:

Outlook pop-up control settings

When testing this sample, pay attention to the Caption property of the New popup: whatever value it has, it doesn't change the name of the New popup in Outlook. This is how Add-in Express connects to existing command bar controls.

Step 9. Customizing Outlook context menu

Use the ADXContextMenu component to customize a context menu of your Outlook add-in. You use this component exactly in the same way as you use the main menu components. Note that for Office main and context menus, the only available control types are button and popup.

Outlook Context Menu component

The sample add-in described here adds a custom item to the Folder Context Menu command bar that implements the context menu which is shown when you right-click a folder in the folder tree.

Also, you can customize many Ribbon-based context menus in Outlook 2010. The Add ADXRibbonContextMenu command of the add-in module adds an ADXRibbonContextMenu component that allows specifying Ribbons that supply context menu names for the ContextMenuNames property. You use the ContextMenuNames property editor to choose the context menu(s) that will display your custom controls specified in the Controls property.

Ribbon context menu properties

Ribbon context menu properties

Step 10. Adding custom task panes in Outlook 2003 - 2010

First you add an Add-in Express Outlook Form to your project and then you add an Outlook Forms Manager component onto your Outlook add-in module. Finally, you add an item to the Items collection of the manager component and set the following properties of the item:

Adding a custom task pane to your Outlook add-in

  • ExplorerItemTypes = Mail - your form will be shown for all mail folders
  • ExplorerLayout = BottomSubpane - the task pane will be shown below the list of mails in Outlook Explorer
  • InspectorItemTypes = Mail - an instance of the form will be shown whenever you open an e-mail
  • InspectorLayout = BottomSubpane - your task pane will be shown to the right of the message body
  • AlwaysShowHeader = True - the header containing the icon (a 16x16 .ico) and the caption of your form will be shown for your form even if it is a single form in the given region
  • CloseButton = True - the header will contain the Close button; a click on it generates the OnADXBeforeCloseButtonClick event of the form
  • FormClassName = OutlookAddin1.ADXOlForm1 - the class name of the form

Find more about custom Outlook task panes.

Step 11. Accessing Outlook objects

To access Outlook objects, add the following method to the add-in module:


Friend Function GetSubject(ByVal InspectorOrExplorer As Object) As String
    Dim result As String = ""
    If InspectorOrExplorer Is Nothing Then Return result

    Dim outlookItem As Object = Nothing
    Dim mailItem As Outlook.MailItem = Nothing
    Dim selection As Outlook.Selection = Nothing

    If TypeOf InspectorOrExplorer Is Outlook.Explorer Then
        Try
            selection = CType(InspectorOrExplorer, Outlook.Explorer).Selection
            If selection.Count > 0 Then outlookItem = selection.Item(1)
        Catch
        Finally
            If selection IsNot Nothing Then Marshal.ReleaseComObject(selection)
        End Try
    ElseIf TypeOf InspectorOrExplorer Is Outlook.Inspector Then
        Try
            outlookItem = CType(InspectorOrExplorer, _
                Outlook.Inspector).CurrentItem
        Catch
        End Try
    End If

    If outlookItem IsNot Nothing Then
        If TypeOf outlookItem Is Outlook.MailItem Then
            mailItem = CType(outlookItem, Outlook.MailItem)
            result = mailItem.Subject
        End If
        Marshal.ReleaseComObject(outlookItem)
    End If
    Return result
End Function

The code of the GetSubject method highlights the following:

  • Outlook 2007 fires an exception when you try to obtain the Selection object in some situations.
  • There may be no items in the Selection object.

For information about the use of Marshal.ReleaseComObject, see Releasing COM objects.

Now select the buttons added in previous steps in the Properties window combo one by one and create the following event handlers:


Private Sub DefaultActionInExplorer(ByVal sender As System.Object) _
   Handles AdxCommandBarButton1.Click
    Dim explorer As Outlook.Explorer = Me.OutlookApp.ActiveExplorer
    If explorer IsNot Nothing Then
        MsgBox("The subject is:" _
           + vbCrLf _
           + GetSubject(explorer))
        Marshal.ReleaseComObject(explorer)
    End If
End Sub

Private Sub DefaultActionInInspector(ByVal sender As System.Object) _
         Handles AdxCommandBarButton2.Click, AdxCommandBarButton6.Click
    Dim inspector As Outlook.Inspector = Me.OutlookApp.ActiveInspector
    If inspector IsNot Nothing Then
        MsgBox("The subject is:" _
           + vbCrLf _
           + GetSubject(inspector))
        Marshal.ReleaseComObject(inspector)
    End If
End Sub

Private Sub AdxRibbonButton1_OnClick(ByVal sender As System.Object, _
    ByVal control As AddinExpress.MSO.IRibbonControl, _
    ByVal pressed As System.Boolean) Handles AdxRibbonButton1.OnClick
    DefaultActionInInspector(Nothing)
End Sub

Step 12. Handling Outlook events

The Add-in Module provides all application-level Outlook events. For instance, the following code handles the BeforeFolderSwitch event of the Outlook Explorer class:


   Private Sub ADXModule1_ExplorerBeforeFolderSwitch _
      (ByVal sender As Object, _
      ByVal e As _
             AddinExpress.VSTO.ADXOlExplorerBeforeFolderSwitchEventArgs) _
      Handles Me.ExplorerBeforeFolderSwitch
      MsgBox("You are switching to the " + e.NewFolder.Name + " folder")
   End Sub

The form added in Step 10. Adding a custom task pane in Outlook 2010 - 2003 also provides a number of Outlook events. Say, you can handle the ADXSelectionChange event as follows (requires adding a label onto the form):


Private Sub ADXOlForm1_ADXSelectionChange() Handles MyBase.ADXSelectionChange
    Dim theModule As OutlookAddin1.ADXModule = _
        CType(Me.AddinModule, OutlookAddin1.ADXModule)
    If Me.ExplorerObj IsNot Nothing Then
        Me.Label1.Text = theModule.GetSubject(Me.ExplorerObj)
    ElseIf Me.InspectorObj IsNot Nothing Then
        Me.Label1.Text = theModule.GetSubject(Me.InspectorObj)
    End If
End Sub

Step 13. Handling events of Outlook Items object

The Outlook MAPIFolder class provides the Items collection. This collection provides the following events: ItemAdd, ItemChange, and ItemRemove. To process these events, you use the Outlook Items Events Class located in the Add-in Express Items folder in the Add New Item dialog:

Outlook Items Events component

This adds the OutlookItemsEventsClass1.vb class to the add-in project. You handle the ItemAdd event by entering some code into the ProcessItemAdd procedure of the class:


Imports System

'Add-in Express for VSTO Outlook Items Events Class
Public Class OutlookItemsEventsClass1
   Inherits AddinExpress.VSTO.ADXOutlookItemsEvents
   Public Sub New(ByVal ADXModule As AddinExpress.VSTO.ADXAddinModule)
      MyBase.New(ADXModule)
   End Sub
   Public Overrides Sub ProcessItemAdd(ByVal Item As Object)
      MsgBox("The item with subject '" + Item.Subject + _
         "' has been added to the Inbox folder")
   End Sub
   Public Overrides Sub ProcessItemChange(ByVal Item As Object)
      'TODO: Add some code
   End Sub
   Public Overrides Sub ProcessItemRemove()
      'TODO: Add some code
   End Sub
End Class

This requires adding the following declarations and code to the Add-in Module:


Dim ItemsEvents As OutlookItemsEventsClass1 = _
          New OutlookItemsEventsClass1(Me)
...
   Private Sub ADXModule1_OnBeginShutdown(ByVal sender As Object, _
         ByVal e As System.EventArgs) Handles Me.OnBeginShutdown
      If ItemsEvents IsNot Nothing Then
         ItemsEvents.RemoveConnection()
         ItemsEvents = Nothing
      End If
   End Sub

   Private Sub ADXModule1_OnStartupComplete(ByVal sender As Object, _
         ByVal e As System.EventArgs) Handles Me.OnStartupComplete
      ItemsEvents.ConnectTo( _
            AddinExpress.VSTO.ADXOlDefaultFolders.olFolderInbox, True)
   End Sub

Step 14. Adding Outlook folder property pages

Unlike other Office applications, Outlook allows you to add custom option pages to the Options dialog box (the Tools | Options menu) and / or to the Properties dialog box of any folder. To automate this task, Add-in Express provides the Outlook Property Page component. You find it in the Add New Item dialog box.

Outlook Options page component

Click the Add button to add a new property page instance, a descendant of the ADXOlPropertyPage class that implements the IPropertyPage interface:


Imports System.Runtime.InteropServices

'Add-in Express for VSTO Outlook Options Page
Public Class OptionsPage1
   Inherits AddinExpress.VSTO.ADXOlPropertyPage

#Region " Component Designer generated code "

   Public Sub New()
      MyBase.New()

      'This call is required by the Component Designer
      InitializeComponent()

      'Add any initialization after the InitializeComponent() call

   End Sub

   'Clean up any resources being used
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub

   'Required by designer
   Private components As System.ComponentModel.IContainer

   'Required by designer - do not modify
   'the following method
   <SYSTEM.DIAGNOSTICS.DEBUGGERSTEPTHROUGH()> _
   Private Sub InitializeComponent()
      components = New System.ComponentModel.Container()
      '
      'OptionsPage1
      '
      Me.Name = "OptionsPage1"
      Me.Size = New System.Drawing.Size(413, 358)
   End Sub

#End Region
End Class

You can customize the page as an ordinary form: add the controls and handle their events. To add a property page to the <FolderName> Properties dialog box of an Outlook folder(s), you do the following:

  • In the AddinModule properties, run the editor of the FolderPages property.
  • Click the Add button.
  • Specify the folder you need in the FolderName property.
  • Set the PageType property to the PropertyPage component you've added.
  • Specify the Title property and close the dialog box.

Folder options page component settings

The screenshot above shows the settings you need to display your page in the Folder Properties dialog for all Mail folders (FolderName = '*' and ItemTypes = Mail). In order to limit the property page to the Inbox folder only, change the code of the OnStartupComplete event in the Add-in Module as follows:


Private Sub ADXModule1_OnStartupComplete(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles Me.OnStartupComplete
      ItemsEvents.ConnectTo(_
         AddinExpress.VSTO.ADXOlDefaultFolders.olFolderInbox, True)
      Dim ns As Outlook.NameSpace = Me.OutlookApp.GetNamespace("Mapi")
      Dim folder As Outlook.MAPIFolder = _
         ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
      Dim FullPath As String = folder.FolderPath
      ' remove leading backslashes
      Me.FolderPages.Item(0).FolderName = _
         FullPath.Substring(2, FullPath.Length - 2)
      Marshal.ReleaseComObject(folder)
      Marshal.ReleaseComObject(ns)
   End Sub

In order to control the events for the folder, add a checkbox to the page and handle its CheckedChanged event as well as the Dirty, Apply, and Load events of the page as follows:

  ...
   Friend WithEvents CheckBox1 As System.Windows.Forms.CheckBox
   Private TrackStatusChanges As Boolean
   ...
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
   If Not TrackStatusChanges Then Me.OnStatusChange()
End Sub

Private Sub OptionsPage1_Apply(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Apply
   CType(AddinExpress.VSTO.ADXOutlookModule.Instance, _
      OutlookAddIn1.ADXModule1).IsFolderTracked = _
         Me.CheckBox1.Checked
End Sub

Private Sub OptionsPage1_Dirty(ByVal sender As Object, _
   ByVal e As AddinExpress.VSTO.ADXDirtyEventArgs) Handles Me.Dirty
   e.Dirty = True
End Sub

Private Sub OptionsPage1_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load
   TrackStatusChanges = True
   Me.CheckBox1.Checked = _
      CType(AddinExpress.VSTO.ADXOutlookModule.Instance, _
      OutlookAddIn1.ADXModule1).IsFolderTracked
   TrackStatusChanges = False
End Sub

Finally, you add the following property to the AddinModule code:

...
   Friend Property IsFolderTracked() As Boolean
      Get
         Return ItemsEvents.IsConnected
      End Get
      Set(ByVal value As Boolean)
         If value Then
            ItemsEvents.ConnectTo _
               (AddinExpress.VSTO.ADXOlDefaultFolders.olFolderInbox, True)
         Else
            ItemsEvents.RemoveConnection()
         End If
      End Set
   End Property

Adding a page to the Outlook Options dialog

To add this or other property page to the main Options dialog box, you use the PageType and PageTitle properties of the add-in module. See also Outlook property page.

Step 15. Intercepting keyboard shortcut

To intercept a keyboard shortcut, you add an ADXKeyboardShortcut component to the COM Add-in module using the Add Keyboard Shortcut command of the module.

Outlook Keyboard shortcut component

In the Properties window you select (or enter) the desired shortcut in the ShortcutText property. We chose the shortcut for the Send button in the mail Inspector's Standard command bar. It is Ctrl+Enter.

HandleShortcuts property

To use keyboard shortcuts, you need to set the HandleShortcuts property of AddinModule to true.

Now you handle the Action event of the component:


Private Sub AdxKeyboardShortcut1_Action(ByVal sender As System.Object) _
      Handles AdxKeyboardShortcut1.Action
      MsgBox("You've pressed " + _
         CType(sender, AddinExpress.VSTO.ADXKeyboardShortcut).ShortcutText)
   End Sub

   End Property

See also how to create custom application-level keyboard shortcuts.

Step 16. Running your VSTO Outlook add-in

Save the project and build it. Restart Outlook and see your sample Outlook plug-in with custom option page(s), command bars, ribbon tabs, and custom task panes. You find your add-in in the COM Add-ins dialog.

Step 17. Debugging the Outlook add-in

To debug your add-in, just press F5 or select the Start Debugging item in the Debug menu of Visual Studio.

Step 18. Deploying your Outlook add-in

Build the setup project, transfer the files to the target PC and run the setup.exe. You can find another bit of useful information in Deploying Add-in Express based VSTO solutions.

Creating Office plugins in VSTO <<

>> Custom task panes for Outlook and Excel