A FAQ is now included at the bottom of this article.
Introduction
Recently, I wrote an Outlook2000 COM addin as a part of a project to build a CRM tool. While coding the project, I thought this would make a good topic for an article especially since most of the Office related stuff I found on the Internet were VB/VBA related and almost none with ATL.
The code in this article is not optimized and the general approach has been kept simple for the reader to follow. Since I took quite sometime to write this, despite my best efforts, in case of any errors or omissions, kindly drop me a mail. If you like this article or found it interesting read, I'd be glad if you could give me a good rating and mail me your comments.:) Thanks.
Overview
Through this article/tutorial, we will learn how to program an Outlook2000/2K+ COM addin using a pure ATL COM object. We'll startout by writing a basic functional COM addin. Then I'll show you how to add standard UI elements like toolbars and menu items to Outlook and how to respond to their events. Next we'll add our own propertysheet for the addin to Outlook's Tools->Options. Along the way we'll see the relevant registry keys and also take a look at useful features of the ATL Wizards and learn to use them effectively
Although we'll be writing an Outlook2000 COM addin, COM addins for other Office2000 applications like Word,Access etc can be built very similarly. Except a couple of minor things like registry keys, for instance, the fundamentals remain the same.
I'm assuming that you are a VC++ COM programmer, and have had some experience with ATL based component development and OLE/Automation, although this is not strictly necessary. To build and test the addin, you must have MS Office 2000 installed on your system, or at least Outlook2K.The project code has been built with VC++ 6.0 sp3+/ATL3.0 and tested on Win2K with Office 2000 installed.
Getting started
An Office addin is a COM Automation component that dynamically extends/enhances and controls any Office suite of applications. Microsoft Office 2000 and later support a new, uniform design architecture for building such application add-ins. Typically such addins are housed in ActiveX dlls(inproc server) and can be dynamically loaded and unloaded by the user through the main application.
An Office COM addin must implement the IDTExtensibility2 interface. The IDTExtensibility2 dispinterface is defined in the MSADDin Designer typelibrary (MSADDNDR.dll/MSADDNDR.tlb) file usually present at the location <drive>/Program Files/Common Files/Designer.
The interface definition looks like:
Expand code snippet
enum {
ext_cm_AfterStartup = 0,
ext_cm_Startup = 1,
ext_cm_External = 2,
ext_cm_CommandLine = 3
} ext_ConnectMode;
enum {
ext_dm_HostShutdown = 0,
ext_dm_UserClosed = 1
} ext_DisconnectMode;
...
...
...
interface _IDTExtensibility2 : IDispatch {
[id(0x00000001)]
HRESULT OnConnection(
[in] IDispatch* Application,
[in] ext_ConnectMode ConnectMode,
[in] IDispatch* AddInInst,
[in] SAFEARRAY(VARIANT)* custom);
[id(0x00000002)]
HRESULT OnDisconnection(
[in] ext_DisconnectMode RemoveMode,
[in] SAFEARRAY(VARIANT)* custom);
[id(0x00000003)]
HRESULT OnAddInsUpdate([in] SAFEARRAY(VARIANT)* custom);
[id(0x00000004)]
HRESULT OnStartupComplete([in] SAFEARRAY(VARIANT)* custom);
[id(0x00000005)]
HRESULT OnBeginShutdown([in] SAFEARRAY(VARIANT)* custom);
};
All COM add-ins inherit from IDTExtensibility2 interface and must implement each of its five methods.
OnConnection and OnDisconnection, as their names suggest, are called when the addin loads and unloads from memory. The addin can be loaded either during application startup, by the user or through automation and the enumerator ext_Connect denotes these connection modes.OnAddinsUpdate is called when a set of COM addins changes.OnStartupComplete is called only if the addin was loaded during application startup and OnBeginShutdown is called if the addin was disconnected on host application shutdown.
Registering an addin
To register the COM addin with the host application, we also need to create a couple of registry subkeys under the hive
HKEY_CURRENT_USER\Software\Microsoft\Office\<TheOfficeApp>\Addins\<ProgID>
where ProgID refers to the addin COM object's unique Programmatic Identifier(ProgID). The other entries through which the addin can provide information about itself and specify loading options to the host app are:
FriendlyName - a string value - this is the addin's name as displayed by the host app.
Description - a string value - a description of the addin.
LoadBehavior - a DWORD value. - A combination of values that determine how the addin will be loaded by the host app.Set to 0x03 to load on app startup or 0x08 for user controlled activation.
CommandLineSafe - a DWORD value. Set to 0x01(TRUE) or 0x00(FALSE).
For a full description of the all values and options, please consult MSDN documentation.
Building a minimal COM addin
OK, now we know enough to go ahead and code a minimal Outlook2K COM addin.To build the addin project files fireup VC++ IDE, create a new ATL COM Appwizard project and name it OutlookAddin. Remember,if you name it anything else it probably wouldn't work.(just kidding!)
In the follwing Appwizard Step 1 of 1 dialog, accept the default Server Type Dynamic Link Library(DLL),check Allow merging of proxy-stub code to enable this option and click Finish. Then click OK to generate the project files.
Next goto Insert->New ATL Object menu and insert a new ATL simple object to the project by choosing Objects from Category and Simple Object from Objects list in the ATL Object Wizard dialog. Click Next and type Addin as ShortName.In the Attributes tab check Support ISupportErrorInfo. Accept the default options for the rest and click OK.
So far the Wizard has given us an Automation-compatible,dispinterface-savvy inproc COM object housed in a dll. By default,a registry script(.rgs) to add the COM object specific registry entries have also been handed to us. Build the project and checkout if everything is in order.
If you are the eager-beaver type like me, you still need to compile your project's .idl file at the very least before moving on . So do that now.
Next we will write our addin specific code to implement IDTExtensibility2.This is where we let the Implement Interface ATL Wizard kick and make our life a lot easier. In ClassView right-click on CAddin class and choose Implement Interface. This brings up the ATL Implement Interface Wizard.Next click on Add Typelib and in the Browse Typelibraries dialog, scroll down and check Microsoft Add-in Designer(1.0) and click OK. Next check _IDTExtensibility2 interface from the list under AddinDesignerObjects tab of Implement Interface dialog and click OK.
The wizard implements the selected interface for us by adding a default implementation for each of the 5 methods of _IDTExtensibility2 to the CAddin class and updating the COM_INTERFACE_MAP(). Of course each of the methods just returns E_NOTIMPL and it is upto us to add code to do something useful. But for now, our functional COM addin is ready, except the for the necessary registry entries which we'll add next.
To register our addin with the host application,in this case Outlook2000, open the project's Addin.rgs registry script file (under FileView->Resource Files) and add the following to the end of the file.
HKCU
{
Software
{
Microsoft
{
Office
{
Outlook
{
Addins
{
'OutlookAddin.Addin'
{
val FriendlyName = s 'ADOutlook2K Addin'
val Description = s 'ATLCOM Outlook Addin'
val LoadBehavior = d '00000008'
val CommandLineSafe = d '00000000'
}
}
}
}
}
}
}
Since we want our addin to load at a startup, LoadBehavior is set to 3.Now build the project. If everything is in order, the project gets built successfully and registers the addin. To test the addin, either run the project and specify the fullpath to Outlook2K(\Program Files\Microsoft Office\Office\Outlook.exe) in Executable for Debug Session, or run Outlook2K outside the VC++ IDE after you have registered the dll. To check if our addin has been registered successfully, in Outlook, goto Tools->Options and under Other tab click Advanced Options->COM Addins. An entry for our COM addin should have been added to the Addins Available list; the string is what we specified as 'FriendlyName' in our registry script.
While an addin can be programmed for different uses, there are certain common tasks. Typically, this includes adding UI elements like toolbars/toolbands and menu items to Outlook, through which the user can control the addin. By clicking on these buttons and menu items, the user can access the addin's functionality. So next up we'll tackle such toolbar and menu item additions.
Command and Conquer
In Office applications, menus and toolbars are combined into a fully programmable collection called CommandBars. CommandBars are common sharable programmable objects that are exposed by all Office applications as a part of it's object model . CommandBars represent a unified mechanism through which individual toolbars and menu items can be added to the corresponding application. Each CommandBars collection comprises of individual CommandBar objects. .Each CommandBar object again contains a collection of CommandBarControl objects, called CommandBarControls.
CommandBarControls represent a complex hierarchy of objects and subobjects that comprise it's object model. A CommandBarControl can itself contain a CommandBar object, accessible through the CommandBar property of the control. Finally, each CommandBarControl object, within the CommandBarControls collection of controls, can be either a CommandBarComboBox(toolbar combobox), a CommandBarButton(toolbar button), or a CommandBarPopup(popup menu). I wish I could draw a nice diagrammatic representation of the object hierarchy, but I'm terrible at such things(honest!), and I'm sure there are such diagrams depicting MS Office CommandBars object model at MSDN.
In our addin, we'd like to add the following UI elements to Outlook
- 2 toolbar buttons (with bitmaps) in a new toolband.
- a new popup menu item (with bitmap) to 'Tools' menu.
First we need to import Office and Outlook typelibraries to our project. To do this open the project's stdafx.h file and add the following #import directive.
#import "C:\Program Files\Microsoft Office\Office\mso9.dll" \
rename_namespace("Office") named_guids
using namespace Office;
#import "C:\Program Files\Microsoft Office\Office\MSOUTL9.olb"
rename_namespace("Outlook"), raw_interfaces_only, named_guids
using namespace Outlook;
Note: You need to change the paths above to match the location where MSOffice has been installed on your system.
Now that we are all set, let's dig into some code. First the toolband and toolbar buttons.
In the Outlook Object Model, the Application object is at the top of the object hierarchy that represents the entire application. Through it's ActiveExplorer method we get the Explorer object that represents the currently active window. Next we'll use the GetCommandBars method to get the CommandBars object that, as you know, is a collection of all of Outlook's toolbands and menuitems. Then, we simply call Add method of the CommandBars collection with relevant parameters to add a new toolband. Adding new buttons to the toolband is as simple as getting the toolband's CommandBarControls collection and then calling it's Add method. Finally we query the buttons for the CommandBarButton object that we'll use to set button styles, and other button properties like caption, tooltip text etc.
The code snippet is as follows:
Expand code snippet
STDMETHODIMP CAddin::OnConnection(IDispatch * Application,
ext_ConnectMode ConnectMode,
IDispatch * AddInInst, SAFEARRAY * * custom)
{
CComPtr < Office::_CommandBars> spCmdBars;
CComPtr < Office::CommandBar> spCmdBar;
// QI() for _Application
CComQIPtr <Outlook::_Application> spApp(Application);
ATLASSERT(spApp);
// get the CommandBars interface that represents Outlook's
//toolbars & menu items
CComPtr<Outlook::_Explorer> spExplorer;
spApp->ActiveExplorer(&spExplorer);
HRESULT hr = spExplorer->get_CommandBars(&spCmdBars);
if(FAILED(hr))
return hr;
ATLASSERT(spCmdBars);
// now we add a new toolband to Outlook
// to which we'll add 2 buttons
CComVariant vName("OutlookAddin");
CComPtr <Office::CommandBar> spNewCmdBar;
// position it below all toolbands
//MsoBarPosition::msoBarTop = 1
CComVariant vPos(1);
CComVariant vTemp(VARIANT_TRUE); // menu is temporary
CComVariant vEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
//Add a new toolband through Add method
// vMenuTemp holds an unspecified parameter
//spNewCmdBar points to the newly created toolband
spNewCmdBar = spCmdBars->Add(vName, vPos, vEmpty, vTemp);
//now get the toolband's CommandBarControls
CComPtr < Office::CommandBarControls> spBarControls;
spBarControls = spNewCmdBar->GetControls();
ATLASSERT(spBarControls);
//MsoControlType::msoControlButton = 1
CComVariant vToolBarType(1);
//show the toolbar?
CComVariant vShow(VARIANT_TRUE);
CComPtr < Office::CommandBarControl> spNewBar;
CComPtr < Office::CommandBarControl> spNewBar2;
// add first button
spNewBar = spBarControls->Add(vToolBarType,vEmpty,vEmpty,vEmpty,vShow);
ATLASSERT(spNewBar);
// add 2nd button
spNewBar2 = spBarControls->Add(vToolBarType,vEmpty,vEmpty,vEmpty,vShow);
ATLASSERT(spNewBar2);
_bstr_t bstrNewCaption(OLESTR("Item1"));
_bstr_t bstrTipText(OLESTR("Tooltip for Item1"));
// get CommandBarButton interface for each toolbar button
// so we can specify button styles and stuff
// each button displays a bitmap and caption next to it
CComQIPtr < Office::_CommandBarButton> spCmdButton(spNewBar);
CComQIPtr < Office::_CommandBarButton> spCmdButton2(spNewBar2);
ATLASSERT(spCmdButton);
ATLASSERT(spCmdButton2);
// to set a bitmap to a button, load a 32x32 bitmap
// and copy it to clipboard. Call CommandBarButton's PasteFace()
// to copy the bitmap to the button face. to use
// Outlook's set of predefined bitmap, set button's FaceId to //the
// button whose bitmap you want to use
HBITMAP hBmp =(HBITMAP)::LoadImage(_Module.GetResourceInstance(),
MAKEINTRESOURCE(IDB_BITMAP1),IMAGE_BITMAP,0,0,LR_LOADMAP3DCOLORS);
// put bitmap into Clipboard
::OpenClipboard(NULL);
::EmptyClipboard();
::SetClipboardData(CF_BITMAP, (HANDLE)hBmp);
::CloseClipboard();
::DeleteObject(hBmp);
// set style before setting bitmap
spCmdButton->PutStyle(Office::msoButtonIconAndCaption);
HRESULT hr = spCmdButton->PasteFace();
if (FAILED(hr))
return hr;
spCmdButton->PutVisible(VARIANT_TRUE);
spCmdButton->PutCaption(OLESTR("Item1"));
spCmdButton->PutEnabled(VARIANT_TRUE);
spCmdButton->PutTooltipText(OLESTR("Tooltip for Item1"));
spCmdButton->PutTag(OLESTR("Tag for Item1"));
//show the toolband
spNewCmdBar->PutVisible(VARIANT_TRUE);
spCmdButton2->PutStyle(Office::msoButtonIconAndCaption);
//specify predefined bitmap
spCmdButton2->PutFaceId(1758);
spCmdButton2->PutVisible(VARIANT_TRUE);
spCmdButton2->PutCaption(OLESTR("Item2"));
spCmdButton2->PutEnabled(VARIANT_TRUE);
spCmdButton2->PutTooltipText(OLESTR("Tooltip for Item2"));
spCmdButton2->PutTag(OLESTR("Tag for Item2"));
spCmdButton2->PutVisible(VARIANT_TRUE);
//......
//......
//code to add new menubar to be added here
//read on
//......
Similarly to add a new menu item to Outlook's Tools menu, we do the following. The ActiveMenuBar property of the CommandBars collection returns a CommandBar object that represents the active menubar in the container application(i.e. Outlook for us).Next we query for the active menubar's controls collection (CommandBarControls) through GetControls method. Since we want to add a popup menuitem to Outlook's Tools(6th position) menu,we retrieve the 6th item in the activemenubars control collection and straightaway call Add method to create a new menuitem and attach it to Tools menu. There's really nothing new here.
The corresponding code snippet is as follows:
Expand code snippet
//......
//code to add toolbar here
//......
_bstr_t bstrNewMenuText(OLESTR("New Menu Item"));
CComPtr < Office::CommandBarControls> spCmdCtrls;
CComPtr < Office::CommandBarControls> spCmdBarCtrls;
CComPtr < Office::CommandBarPopup> spCmdPopup;
CComPtr < Office::CommandBarControl> spCmdCtrl;
// get CommandBar that is Outlook's main menu
hr = spCmdBars->get_ActiveMenuBar(&spCmdBar);
if (FAILED(hr))
return hr;
// get menu as CommandBarControls
spCmdCtrls = spCmdBar->GetControls();
ATLASSERT(spCmdCtrls);
// we want to add a menu entry to Outlook's 6th(Tools) menu //item
CComVariant vItem(5);
spCmdCtrl= spCmdCtrls->GetItem(vItem);
ATLASSERT(spCmdCtrl);
IDispatchPtr spDisp;
spDisp = spCmdCtrl->GetControl();
// a CommandBarPopup interface is the actual menu item
CComQIPtr < Office::CommandBarPopup> ppCmdPopup(spDisp);
ATLASSERT(ppCmdPopup);
spCmdBarCtrls = ppCmdPopup->GetControls();
ATLASSERT(spCmdBarCtrls);
CComVariant vMenuType(1); // type of control - menu
CComVariant vMenuPos(6);
CComVariant vMenuEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
CComVariant vMenuShow(VARIANT_TRUE); // menu should be visible
CComVariant vMenuTemp(VARIANT_TRUE); // menu is temporary
CComPtr < Office::CommandBarControl> spNewMenu;
// now create the actual menu item and add it
spNewMenu = spCmdBarCtrls->Add(vMenuType, vMenuEmpty, vMenuEmpty,
vMenuEmpty, vMenuTemp);
ATLASSERT(spNewMenu);
spNewMenu->PutCaption(bstrNewMenuText);
spNewMenu->PutEnabled(VARIANT_TRUE);
spNewMenu->PutVisible(VARIANT_TRUE);
//we'd like our new menu item to look cool and display
// an icon. Get menu item as a CommandBarButton
CComQIPtr < Office::_CommandBarButton> spCmdMenuButton(spNewMenu);
ATLASSERT(spCmdMenuButton);
spCmdMenuButton->PutStyle(Office::msoButtonIconAndCaption);
// we want to use the same toolbar bitmap for menuitem too.
// we grab the CommandBarButton interface so we can add
// a bitmap to it through PasteFace().
spCmdMenuButton->PasteFace();
// show the menu
spNewMenu->PutVisible(VARIANT_TRUE);
return S_OK;
}
With that under our belt, it's F5 time. If everything has gone OK, the project builds successfully and you are about to get a first glimpse of your addin in action(if you haven't already, that is). Since we are going to run Outlook to test our addin, in the 'Executable for Debug' dialog, browse to the current path of Outlook executable (Outlook.exe) and we're finally ready to go. In Outlook goto Tools->Options and under the Other tab, click Advanced Options. From the Advanced Options dialog, click on COM Addins button. Next check the entry for our addin in the Addins Available listbox and click OK. As our addin is loaded a new docked toolband with 2 buttons gets created.Also checkout the cool looking menu item that you just added to Outlook's Tools menu.
There it is!! Not only have you programmed a working Outlook addin, and one that extends Outlook with cool looking toolbars and menu item, thanks to ATL, your < 50Kb addin also qualifies as the leanest, meanest COM server in town. So savour the moment! :)
Lord of the (disp) Sinks
Putting together a couple of toolbars and menu items, by themselves, are not very useful unless we can write command handlers that respond to their events. So let's get right to it. Of course here, on click of the different buttons and menu items, we'll be just popping up simple messageboxes. But this is where you'd code your addins functionality. From CRM tools, automated contact management, mail notification and filtering to advanced document management systems to full fledged applications, COM addins can perform an endless variety of tasks.
The CommandBarButton control exposes a Click event that is triggered when a user clicks a command bar button. We are going to use this event to run code when the user clicks the toolbar buttons or the menu item. For this, our COM object has to implement an event sink interface. For the CommandBarButton control, this event dispinterface is _CommandBarButtonEvents.The Click method is declared as
//...