VSTO add-ins and the NewInspector Event

VSTO add-ins for Outlook are great. It's much easier than implementing the IDTExtensibility2 interface. Basically, the way it works is this (actually, Andrew Whitechapel does a much better job explaining than I will, so here you go): the AddinLoader.dll keeps a "dormant" list of add-ins that tried to load when the Outlook.exe process is started.

If there's UI (if there are any Explorers or Inspectors visible), then it fires the _Startup event. If there is no UI (like when using the Outlook View Control or ActiveSync), then it doesn't fire _Startup until the first Inspector or Explorer is made visible.

Once the last UI element is closed, then VSTO fires the _Shutdown event.

A typical operation one would usually perform (and a reason for creating an add-in in the first place) is to add some sort of UI to an Inspector or Explorer, such as a button on a command bar or a menu item. In a traditional COM add-in, the way you would do this would be to hook in to the Inspectors.NewInspector event and in the handler for that event, you'd add your UI. And that works great. It works great in VSTO also, except the first time.

Because VSTO itself is waiting until the NewInspector event fires (in scenarios where Outlook.exe is started with no UI) to fire the _Startup event on your VSTO add-in, it is too late to bind to the event yourself (it's already been fired). So what happens is that the first time an Inspector opens, your button is not added to the CommandBar, but the second time it is!

The way to get around this problem is simple. Remember that the _Startup event is fired during the NewInspector event. So in your _Startup code, just check the Inspectors.Count property and if it's greater than 0, go ahead and add your button (or whatever)! In subsequent calls to the NewInspector, your code will fire.

Here's an example:

private Microsoft.Office.Interop.Outlook.Inspectors objInspectors;

private void ThisApplication_Startup(object sender, System.EventArgs e)
{
objInspectors = this.Inspectors;
objInspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(objInspectors_NewInspector);
if(objInspectors.Count >= 1)
AddCustomUI();
}

private void ThisApplication_Shutdown(object sender, System.EventArgs e) {

}

private void objInspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector){
AddCustomUI();
}

private void AddCustomUI(){
//...do your add button thing or whatever here
}