Search code examples
c#outlookvstooutlook-addin

C# VSTO Outlook ItemSend Event execution order


I am using VSTO to create an event when an email is sent. The goal is change Attachments.

I already have other addins that run in the ItemSend event, but the problem is, I want my addin to run first. As I've read, there is no execution order for the Outlook addins sent event, but there must be some order even if only by name or guid...

I tried this solution (the problem is, if I have 2 mail windows open, the first window doesn´t run the event ... :( there is some overwrite event problem)

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.Inspectors.NewInspector += new InspectorsEvents_NewInspectorEventHandler(Custom_Inspector);
    
    //This run in the end off all ItemSend Events.... :(
    //this.Application.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(MyFunction2);
}
        
private void Custom_Inspector(Inspector Inspector)
{
    if (Inspector != null && Inspector.CurrentItem != null && Inspector.CurrentItem is Outlook.MailItem)
    {
        Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
                

        if (mailItem.EntryID == null)
        {
           ((ItemEvents_10_Event)mailItem).Send += new ItemEvents_10_SendEventHandler(MyFunction);
       }

    }
}
        
void MyFunction(ref bool Cancel)
{
         
    MailItem mailItemContext = ((Inspector)this.Application.ActiveWindow()).CurrentItem as MailItem;

    if (mailItemContext != null)
    {
         //my custom code here     
    }
}

Solution

  • this.Application.Inspectors.NewInspector += new InspectorsEvents_NewInspectorEventHandler(Custom_Inspector);

    To get the NewInspector event of the Inspectors class fired you need to keep the source object alive, i.e. prevent it from swiping by the garbage collector. So, I'd recommend declaring the an instance of the Inspectors class at the global scope - at the class level.

    The Outlook object model doesn't provide anything for changing the order of events. From my experience add-ins are loaded based on the ProgID value (sorted in the alphabetical order) and events are fired in the reverse order, i.e. a LIFO queue.