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:
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:
STDMETHODIMP CAddin::OnConnection(IDispatch * Application,
ext_ConnectMode ConnectMode,
IDispatch * AddInInst, SAFEARRAY * * custom)
{
CComPtr < Office::_CommandBars> spCmdBars;
CComPtr < Office::CommandBar> spCmdBar;
CComQIPtr <Outlook::_Application> spApp(Application);
ATLASSERT(spApp);
CComPtr<Outlook::_Explorer> spExplorer;
spApp->ActiveExplorer(&spExplorer);
HRESULT hr = spExplorer->get_CommandBars(&spCmdBars);
if(FAILED(hr))
return hr;
ATLASSERT(spCmdBars);
CComVariant vName("OutlookAddin");
CComPtr <Office::CommandBar> spNewCmdBar;
CComVariant vPos(1);
CComVariant vTemp(VARIANT_TRUE);
CComVariant vEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
spNewCmdBar = spCmdBars->Add(vName, vPos, vEmpty, vTemp);
CComPtr < Office::CommandBarControls> spBarControls;
spBarControls = spNewCmdBar->GetControls();
ATLASSERT(spBarControls);
CComVariant vToolBarType(1);
CComVariant vShow(VARIANT_TRUE);
CComPtr < Office::CommandBarControl> spNewBar;
CComPtr < Office::CommandBarControl> spNewBar2;
spNewBar = spBarControls->Add(vToolBarType,vEmpty,vEmpty,vEmpty,vShow);
ATLASSERT(spNewBar);
spNewBar2 = spBarControls->Add(vToolBarType,vEmpty,vEmpty,vEmpty,vShow);
ATLASSERT(spNewBar2);
_bstr_t bstrNewCaption(OLESTR("Item1"));
_bstr_t bstrTipText(OLESTR("Tooltip for Item1"));
CComQIPtr < Office::_CommandBarButton> spCmdButton(spNewBar);
CComQIPtr < Office::_CommandBarButton> spCmdButton2(spNewBar2);
ATLASSERT(spCmdButton);
ATLASSERT(spCmdButton2);
HBITMAP hBmp =(HBITMAP)::LoadImage(_Module.GetResourceInstance(),
MAKEINTRESOURCE(IDB_BITMAP1),IMAGE_BITMAP,0,0,LR_LOADMAP3DCOLORS);
::OpenClipboard(NULL);
::EmptyClipboard();
::SetClipboardData(CF_BITMAP, (HANDLE)hBmp);
::CloseClipboard();
::DeleteObject(hBmp);
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"));
spNewCmdBar->PutVisible(VARIANT_TRUE);
spCmdButton2->PutStyle(Office::msoButtonIconAndCaption);
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);
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:
_bstr_t bstrNewMenuText(OLESTR("New Menu Item"));
CComPtr < Office::CommandBarControls> spCmdCtrls;
CComPtr < Office::CommandBarControls> spCmdBarCtrls;
CComPtr < Office::CommandBarPopup> spCmdPopup;
CComPtr < Office::CommandBarControl> spCmdCtrl;
hr = spCmdBars->get_ActiveMenuBar(&spCmdBar);
if (FAILED(hr))
return hr;
spCmdCtrls = spCmdBar->GetControls();
ATLASSERT(spCmdCtrls);
CComVariant vItem(5);
spCmdCtrl= spCmdCtrls->GetItem(vItem);
ATLASSERT(spCmdCtrl);
IDispatchPtr spDisp;
spDisp = spCmdCtrl->GetControl();
CComQIPtr < Office::CommandBarPopup> ppCmdPopup(spDisp);
ATLASSERT(ppCmdPopup);
spCmdBarCtrls = ppCmdPopup->GetControls();
ATLASSERT(spCmdBarCtrls);
CComVariant vMenuType(1);
CComVariant vMenuPos(6);
CComVariant vMenuEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
CComVariant vMenuShow(VARIANT_TRUE);
CComVariant vMenuTemp(VARIANT_TRUE);
CComPtr < Office::CommandBarControl> spNewMenu;
spNewMenu = spCmdBarCtrls->Add(vMenuType, vMenuEmpty, vMenuEmpty,
vMenuEmpty, vMenuTemp);
ATLASSERT(spNewMenu);
spNewMenu->PutCaption(bstrNewMenuText);
spNewMenu->PutEnabled(VARIANT_TRUE);
spNewMenu->PutVisible(VARIANT_TRUE);
CComQIPtr < Office::_CommandBarButton> spCmdMenuButton(spNewMenu);
ATLASSERT(spCmdMenuButton);
spCmdMenuButton->PutStyle(Office::msoButtonIconAndCaption);
spCmdMenuButton->PasteFace();
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
[id(0x00000001), helpcontext(0x00038271)]
void Click(
[in] CommandBarButton* Ctrl,
[in, out] VARIANT_BOOL* CancelDefault);
Thus all we have to do is implement sink interface/s that will be called by the event source through regular connection point protocol whenever a menu or a toolbar button is clicked. What we get for parameters to our callback method is a pointer to the the source CommandBarButton
object and a boolean value that can be used to accept or negate the default action. As to implementing a dispatch sink interface, that's nothing new and as an ATL programmer you have probably done this a lot of times.
But for the uninitiated, ATL provides 2 template classes IDispEventImpl<>
and IDispEventSimpleImpl<>
for ATL COM objects, that provide an implementation of IDispatch. I prefer the light-weight IDispEventSimpleImpl
cause it doesn't need the extra typelib info. Just derive your class from IDispEventSimpleImpl<>
, set up your sink map, rig up your callback params through _ATL_SINK_INFO
structure and finally call DispEventAdvise
and DispEventUnadvise
to connect and disconnect from the source interface. For our toolbar buttons and menu items, if we were to write a single callback method for all events, then,once we have a pointer to the CommandBarButton
that triggered the event, we can use it's GetCaption
method to get the button text, based on which we can perform some selective action. For this sample however, we'll have one callback per event.
Here's how the code goes:
-
Derive your class from IDispSimpleEventImpl- The first parameter is typically the child window ID incase of activeX controls. For us however, this can be any predefined integer that uniquely identifies the event source (in our case the first toolbar button) <>
class ATL_NO_VTABLE CAddin :
public CComObjectRootEx < CComSingleThreadModel>,
.....
.....
public IDispEventSimpleImpl<1,CAddin,
&__uuidof(Office::_CommandBarButtonEvents>
- Setup the callback- First we define a callback as follows:
void __stdcall OnClickButton(IDispatch *
Ctrl,
VARIANT_BOOL * CancelDefault);
Next we use the _ATL_SINK_INFO structure to describe the callback parameters. Open the Addin.h file and at the top add the following declaration: extern _ATL_FUNC_INFO OnClickButtonInfo;
Next open the Addin.cpp file and add the definition: _ATL_FUNC_INFO OnClickButtonInfo =
{CC_STDCALL,VT_EMPTY,2,{VT_DISPATCH,VT_BYREF | VT_BOOL}};
OnClickButton is very elementary here and looks like: void __stdcall CAddin::OnClickButton(IDispatch*
Ctrl,
VARIANT_BOOL * CancelDefault)
{
USES_CONVERSION;
CComQIPtr<Office::_CommandBarButton> pCommandBarButton(Ctrl);
MessageBox(NULL, "Clicked Button1", "OnClickButton", MB_OK);
}
- The sinkmap We'll setup the sinkmap using the ATL macros
BEGIN_SINK_MAP()
and END_SINK_MAP()
,the sink map to be populated by SINK_ENTRY_XXX
. The sink map basically provides the mapping between a dispid that defines the event and the member function that handles it.
BEGIN_SINK_MAP(CAddin)
SINK_ENTRY_INFO(1, __uuidof(Office::_CommandBarButtonEvents),
0x01,
OnClickButton, &OnClickButtonInfo)
END_SINK_MAP()
Now that everything is in place, we have to connect to and disconnect from the event source with DispEventAdvise()
and DispEventUnadvise()
. Our CAddin
class's OnConnection()
and OnDisconnection()
methods are just the place to do this. The parameters to DispEventAdvise()
and DispEventUnadvise()
are the any interface on the event source and the desired event source interface respectively.
DispEventAdvise((IDispatch*)m_spButton,&DIID__CommandBarButtonEvents);
DispEventUnadvise((IDispatch*)m_spButton);
Similarly implement disp sinks for all your command buttons and menu items, write handlers and connect and disconnect from them as described above. That's all there is to it. If everything went without a hitch, after you rebuild and run the addin, whenever the buttons or menu item is clicked, your respective callback method should be executed.
Adding a propertypage
The last thing we'll learn to do in this tutorial is how to add our own 'Options' property page to Outlook's Tools->Options property sheet.
The catch here is that to add a page to Outlook's Tools->Options menu as a part of our addin, our addin as to implement a propertypage as an activeX control. When the user goes to Tools->Options menu item, the Application object fires an OptionsPagesAdd
event, as exposed through the _ApplicationEvents
dispinterface in the Outlook object model. Extracts from the IDL definition (as described in MSOUTL9.olb viewed through OLE/COM object Viewer) looks like
dispinterface ApplicationEvents
{
....
[id(0x0000f005), helpcontext(0x0050df87)]
void OptionsPagesAdd([in] PropertyPages* Pages);
....
}
[
odl,
uuid(00063080-0000-0000-C000-000000000046),
helpcontext(0x0053ec78),
dual,
oleautomation
]
....
....
interface PropertyPages : IDispatch {
[id(0x0000f000), propget, helpcontext(0x004deb87)]
HRESULT Application([out, retval] _Application** Application);
....
....
[id(0x0000005f), helpcontext(0x00526624)]
HRESULT Add([in] VARIANT Page,
[in, optional] BSTR Title);
[id(0x00000054), helpcontext(0x00526625)]
HRESULT Remove([in] VARIANT Index);
};
The OptionsPagesAdd event passes us a pointer to the PropertyPages dispinterface, whose Add method will finally add the page. The parameters to the Add method are the the ProgID of our control and the new tab caption text. Similarly, to remove a page, call Remove() with the index of the targeted page. Now let's get down to the nitty gritty of it.
Begin by adding a new ATL activex composite control to the project through Insert->New ATL Object. Select Controls from category and Lite Composite Control from Objects listbox and click Next. Enter the ShortName as PropPage and in the Attributes tab, check the Support ISupportErrorInfo option. click on OK to accept all the default options.
Now we are going to implement the PropertyPage interface. So in ClassView, rightclick on CPropPage class, choose Implement Interface and click Add Typelib button as before.This time check the Microsoft Outlook 9.0 Object Library and click OK. From the Interfaces listbox check PropertyPage and click OK.
The Wizard adds default implementations for the 3 methods of PropertyPage, Apply(), get_Dirty() and GetPageInfo().
Now make the following modifications. In the com map, modify the line
COM_INTERFACE_ENTRY(IDispatch)
to
COM_INTERFACE_ENTRY2(IDispatch,IPropPage)
to resolve any ambiguity. Next to implement
IDispatch
, we'll use the
IDispatchImpl<>
template class. So in the
CPropPage
class declaration replace
class ATL_NO_VTABLE CPropPage :
public CComObjectRootEx<CComSingleThreadModel>,
public IDispatchImpl<IPropPage, &IID_IPropPage, &LIBID_TRAILADDINLib>,
....
....
public PropertyPage
with
public IDispatchImpl < Outlook::PropertyPage,&__uuidof(Outlook::PropertyPage),
&LIBID_OUTLOOKADDINLib>
Also remove the redundant #import statement at the top of the PropPage.h file. The typelib has already been imported once in stdafx.h, so this is not needed.
Next we are going to connect and disconnect our addin to ApplicationEvents
dispinterface and write the callback method. You already know what to do. Again use the IDispEventSimpleImpl<>
template to setup the disp sink for ApplicationEvents
, update the sink map and write the callback method for OptionsAddPages
event as described above. Since we are using IDispEventSimpleImpl<>
multiple times, use a typdef for each event interface implementation. Thus the additions are:
extern _ATL_FUNC_INFO OnOptionsAddPagesInfo;
class ATL_NO_VTABLE CAddin :
....
....
public IDispEventSimpleImpl<4,CAddin,&__uuidof(Outlook::ApplicationEvents)>
{
public:
typedef IDispEventSimpleImpl< 4,CAddin,
&__uuidof("outlook::ApplicationEvents">Outlook::ApplicationEvents)> AppEvents;
....
....
....
BEGIN_SINK_MAP(CAddin)
....
SINK_ENTRY_INFO(4,__uuidof(Outlook::ApplicationEvents),
0xf005,OnOptionsAddPages,&OnOptionsAddPagesInfo)
END_SINK_MAP()
public:
void __stdcall OnOptionsAddPages(IDispatch *Ctrl);
};
_ATL_FUNC_INFO OnOptionsAddPagesInfo = (CC_STDCALL,VT_EMPTY,1,{VT_DISPATCH}};
void __stdcall CAddin::OnOptionsAddPages(IDispatch* Ctrl)
{
CComQIPtr<Outlook::PropertyPages> spPages(Ctrl);
ATLASSERT(spPages);
CComVariant varProgId(OLESTR("OutlookAddin.PropPage"));
CComBSTR bstrTitle(OLESTR("OutlookAddin"));
HRESULT hr = spPages->Add((_variant_t)varProgId,(_bstr_t)bstrTitle);
if(FAILED(hr))
ATLTRACE("\nFailed adding propertypage");
}
Finally in OnConnection() and OnDisconnection(), call DispEventAdvise and DispEventUnadvise to connect and disconnect to ApplicationEvents, as before. Now that we have everything in place, rebuild the project. Next hit F5 and goto Outlook's Tools->Options menu. You should see the new tab that we just added. But hangon, when you click on the new tab, instead of the propertypage, a MessageBox tells us that the propertypage cannot be displayed. What happened? Has all our hard work gone to waste? Fear not!
What is happening is that although the propertypage gets created, Outlook doesn't get any information about the propertypage control's keyboard behavior. The default ATL implementation of IOleControl's GetControlInfo
method returns E_NOTIMPL
and consequently the container site cannot process any keystrokes for the propertypage or the contained controls.Hence our page is not displayed. To fix this simply override GetControlInfo()
to return S_OK
.
In the PropPage.h file, add the declaration:
STDMETHOD(GetControlInfo)(LPCONTROLINFO lpCI);
Our overridden method just returns S_OK
, so in the PropPage.cpp file, implement GetControlInfo()
as
STDMETHODIMP CPropPage::GetControlInfo(LPCONTROLINFO lpCI)
{
return S_OK;
}
That's it. Now when you build the project and activate the OutlookAddin tab of Options propertysheet,our new propertypage should get displayed without any errors.
With that we come to the journey's end. The list of things you can do in an Outlook2000 or Office2000 addins are endless. Since, in an addin, you have access to the parent applications internal object model, you can do all the things the app does and more. Plus you can also use other interfaces like MS Assistant that are not directly related to any app. The only limit is your imagination!
Happy addin programming. ;-)
Update
April 02,2003
The response this article has generated on CP has led to this little Q & A section. When I posted this, I was not ready for the barrage of questions and comments that have come up. But I feel, this is a good thing. So keep those questions coming!
Some of the topics and code discussed here are applicable for all Office addins.
- Handling New Inspector Event
- Customize Outlook Menus
Handling New Inspector Event
Q : How do I add custom button/menuitems to Outlook's windows like New->Mail Message window and others?
You can get access to all of Outlook's open windows through Inspector and the Inspectors collection. In particular, InspectorEvent
and InspectorsEvents
dispinterfaces have a host of events that you should handle. Prominent being InspectorsEvents::NewInspector
event, which is fired every time a new Inspector window opens up. It is declared as:
....
dispinterface InspectorsEvents {
properties:
methods:
[id(0x0000f001), helpcontext(0x0050e6f0)]
void NewInspector([in] _Inspector* Inspector);
};
One way to handle the NewInspector event in the addin class is through the ATL IDispatchImpl<>
class template and then handle the NewInspector
event in the class's overridden Invoke()
implementation. We are using IDispatchImpl<>
instead of other ATL classes,only for variation. Here is the code you need to add to your project:
class ATL_NO_VTABLE CAddin :
public CComObjectRootEx < CComSingleThreadModel>,
public CComCoClass < CAddin, &CLSID_Addin>,
...
...
public IDispatchImpl < "Outlook::InspectorEvents">Outlook::InspectorEvents,
&DIID_InspectorsEvents, &LIBID_OLADDINLib>
{
...
...
private:
CComQIPtr <IConnectionPointContainer,&IID_IConnectionPointContainer>
m_spInspectorsCPC;
DWORD m_dwCookie;
};
Next declare your overridden Invoke()
as :
STDMETHOD(Invoke)(DISPID, REFIID, LCID, WORD, DISPPARAMS*,
VARIANT*, EXCEPINFO*, UINT*);
and implement it as :
HRESULT CAddin::Invoke(DISPID dispidMember,REFIID riid,LCID lcid, WORD wFlags,
DISPPARAMS* pDispParams, VARIANT* pvarResult,
EXCEPINFO* pExcepInfo, UINT* puArgErr)
{
if(dispidMember = 0xf001)
{
if (!pDispParams)
return E_INVALIDARG;
if (pDispParams->cArgs > 0)
{
IDispatchPtr pDisp(pDispParams->rgvarg[0].pdispVal);
CComQIPtr<_Inspector> spInspector(pDisp);
CComPtr<_CommandBars> pCmdBars;
HRESULT hr = spInspector->get_CommandBars(&pCmdBars);
if(FAILED(hr))
return hr;
....
....
}
}
};
Finally we need to Advise
and Unadvise
to receive the events. This is done, as before, through the ConnectionPoints. OnConnection()
and OnDisconnection()
is the perfect place to setup the communication. Code to setup the connection goes like :
CComPtr<Outlook::_Inspectors> spInspectors;
hr = spApp->get_Inspectors(&spInspectors);
m_spInspectorsCPC = spInspectors;
ATLASSERT(m_spInspectorsCPC);
CComPtr spCP;
hr = m_spInspectorsCPC->FindConnectionPoint(
__uuidof(Outlook::InspectorsEvents) ,&spCP);
if(FAILED(hr))
return hr;
hr = spCP->Advise(
reinterpret_cast (this),
&m_dwCookie);
if (FAILED(hr))
return hr;
and break it up on OnDisconnection()
:
CComPtr<IConnectionPoint> spCP;
hr = m_spInspectorsCPC->FindConnectionPoint(DIID_InspectorsEvents,&spCP);
if(FAILED(hr))
return hr;
hr = spCP4->Unadvise(m_dwInspectors);
if(FAILED(hr))
return hr;
Provided everything has gone alright, you should be successfully handling the NewInspector
event. The article already shows how to add your own menu and toolbar items.So that's it.
Customize Outlook Menus
Q : How do I make an addition to Outlook's standard menuitems like File,Edit etc.?
Once you get Outlook CommandBars collection, you have a to first search for "Menu Bar" CommandBar and then iterate over it's CommandBarControl collection (which contains File,Edit and other menuitems) to get the target menuitem. Next get it's CommandBarControls collection and add your menuitem. Remember that a CommandBarPopup represents a menuitem and CommandBarButton a toolbaritem. You can also use FindControl()
if you know Outlook menu ID's.
Here's a tiny little method I call during OnConnection()
in my addin, that adds a single menuitem to Outlook's File menu :
HRESULT CAddin::AddNewMenu(_CommandBars *pCmdBars)
{
CComPtr < Office::CommandBar> spNewCmdBar;
HRESULT hr = pCmdBars->get_ActiveMenuBar(&spNewCmdBar);
if (FAILED(hr))
return hr;
int nCount;
hr =pCmdBars->get_Count(&nCount);
if (FAILED(hr))
return hr;
CComBSTR bstrBarName;
CComBSTR bstrToolbarName(OLESTR("Menu Bar"));
CComPtr < Office::CommandBar> pTempCmdBar;
for (int i = 1; i <= nCount; i++)
{
pTempCmdBar = pCmdBars->GetItem(CComVariant(i));
ATLASSERT(pTempCmdBar);
pTempCmdBar->get_Name(&bstrBarName);
if (_bstr_t(bstrBarName, TRUE) == _bstr_t(bstrToolbarName, TRUE))
{
CComPtr< Office::CommandBarControl > spCmdBarCtrl;
CComPtr< Office::CommandBarControls > spCmdBarCtrls;
spCmdBarCtrls = pTempCmdBar->GetControls();
int n = spCmdBarCtrls->GetCount();
for (int j = 1; j < n; j++)
{
spCmdBarCtrl = spCmdBarCtrls->GetItem(CComVariant(j));
CComBSTR bstrCaption;
spCmdBarCtrl->get_Caption(&bstrCaption);
CComBSTR bstrTarget(OLESTR("&File"));
if (_bstr_t(bstrCaption, TRUE) == _bstr_t(bstrTarget, TRUE))
{
CComQIPtr<Office::CommandBarPopup>
spPopup(spCmdBarCtrl->GetControl());
ATLASSERT(spPopup);
CComPtr<CommandBarControls> spCmdCtrls;
spCmdCtrls = spPopup->GetCommandBar()->GetControls();
ATLASSERT(spCmdCtrls);
CComVariant vtType(1);
CComVariant vtEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
CComVariant vtTemp(VARIANT_TRUE);
CComPtr< Office::CommandBarControl > spNewBarCtrl;
spNewBarCtrl = spCmdCtrls->Add(vtType, vtEmpty,
vtEmpty, vtEmpty, vtTemp);
ATLASSERT(spNewBarCtrl);
CComQIPtr< Office::_CommandBarButton >
spButton(spNewBarCtrl);
ATLASSERT(spButton);
spButton->PutCaption(OLESTR("New Menu Item"));
spButton->put_FaceId(4);
spButton->PutStyle(Office::msoButtonIconAndCaption);
spButton->PutVisible(VARIANT_TRUE);
}
}
break;
}
pTempCmdBar.Detach();
}
return S_OK;
}
Q : How do I add a new menubar say, between Outlook's File and Edit menus?
This is somewhat related to the earlier question about additions to standard Outlook menu items. Again, what we need to do is: from Outlook's CommandBars collection, get the active menubar CommandBar,which represents all of Outlook's menus. Next, make an addition to this CommandBar object, through it's CommandBarControls collection. A menu is a CommandBarPopup object(MsoControlType::msoControlPopup = 10
), to which we have to add our menuitems i.e. CommandBarButton(MsoControlType::msoControlButton = 1)
. Also, in the call to CommandBarControls::Add()
, we use the 4th parameter(Before) to specifiy the position as 2(i.e. after File and before Edit)
Like the earlier little function, AddNewMenubar()
adds a "Custom" menubar,between File and Edit, and has a single button(menuitem).
HRESULT CAddin::AddNewMenubar(_CommandBars *pCmdBars)
{
CComPtr < Office::CommandBar > spNewCmdBar;
HRESULT hr = pCmdBars->get_ActiveMenuBar(&spNewCmdBar);
if (FAILED(hr))
return hr;
CComPtr< Office::CommandBarControls > spCtrls;
spCtrls = spNewCmdBar->GetControls();
ATLASSERT(spCtrls);
CComVariant varType(10);
CComVariant vtEmpty(DISP_E_PARAMNOTFOUND, VT_ERROR);
CComVariant vtTemp(VARIANT_TRUE);
CComVariant vtBefore(2);
CComPtr< CommandBarControl > spCtrl;
spCtrl = spCtrls->Add(varType, vtEmpty, vtEmpty, vtBefore, vtTemp);
ATLASSERT(spCtrl);
CComQIPtr< Office::CommandBarPopup > spPopup(spCtrl->GetControl());
ATLASSERT(spPopup);
spPopup->PutCaption(OLESTR("Custom"));
spPopup->PutVisible(VARIANT_TRUE);
CComPtr< Office::CommandBarControls > spCmdBarCtrls;
spCmdBarCtrls = spPopup->GetControls();
CComVariant vType(1);
CComPtr< Office::CommandBarControl > spBarCtrl;
spBarCtrl = spCmdBarCtrls->Add(vType, vtEmpty, vtEmpty, vtEmpty, vtTemp);
ATLASSERT(spBarCtrl);
CComQIPtr< Office::_CommandBarButton > spButton(spBarCtrl);
ATLASSERT(spButton);
spButton->PutCaption(OLESTR("Menu1"));
spButton->PutFaceId(4);
spButton->PutStyle(Office::msoButtonIconAndCaption);
spButton->PutVisible(VARIANT_TRUE);
return S_OK;
}
That's it for now. Cheers! :)
References and Acknowledgements
MSKB Articles:
Q220600 - How to automate Outlook using VC++
Q238228 - Build an Office2000 COM addin in VB
Q259298 - Howto use Outlook Object Model through #import
Q173604 - How to use CommandBars in Outlook solutions
Q182394- How to use CommandBars in Outlook solutions
MSDN articles:
Building COM addins for Outlook2000 - Thomas Rizzo
Developing COM addins for MS Office 2000 - Ed Schultz
MS Newsgroups:
microsoft.public.office.developer.com.addins
microsoft.public.outlook.prog_addins
Books:
ATL Internals - Brent Rector & Chris Sells.
Developer's workshop to COM and ATL 3.0 - Andrew W.Troelsen.
Other:
Renat Garyaev's (garyaev@acm.org) Vernoter sample.
David Mavin, without whom this whole project would not have happened.
People at codeproject.com who have egged me on and provided much needed encouragement.
All the people who developed the fantastic COM object models behind all Office applications. :)
The 80's prog rock/metal band Queensryche's music.