Search code examples
c#event-handlingvstooutlook-addinoutlook-2010

How to Attach to the BeforeAttachmentRead even in Outlook?


I'd like to take some action before users view attachments in Outlook and would like to hook into the BeforeAttachmentRead event in a VSTO plugin. I've seen code that iterates through the inbox and adds the event to each MailItem:

foreach (object o in inbox.Items)
{
 mailItem = o as Outlook.MailItem;
 ...
 ((Outlook.ItemEvents_10_Event)mailItem).BeforeAttachmentRead += new Outlook.ItemEvents_10_BeforeAttachmentReadEventHandler(MailItem_BeforeAttachmentRead);
}

But this seems very inefficient to me (and what about subfolders in the inbox?)

Is there a more efficient way to respond to the BeforeAttachmentRead event?


Solution

  • But this seems very inefficient to me (and what about subfolders in the inbox?)

    I agree it would be.

    I would suggest you subscribe to the selection change event of the Outlook Explorer. Now everytime the user selects something you can check if it is a mailitem (it can be other things) and then subscribe to the BeforeAttachmentRead event. You could actually check for MailItem Attachments count first.. If the mail item does not have attachments then you have nothing to do.

    A few other things to check;

    1. Check that Explorer CurrentFolder.WebViewOn is false;
    2. Check the selection count - you only want to do something if it is 1
    3. A user can select many different things. Before you cast your selection check it actually is of type Outlook.MailItem