Search code examples
c#event-handlingadd-inoutlook-addinoffice-2010

Event Handler not being added to new Mail Items


I'm trying to create a simple Outlook 2010 add-in that responds to new attachment events. The code below only works when I uncomment the MessageBox.Show line. But with it removed it appears not to add the event handler. What am I missing about the program flow that means that a modal message box affect the placement of event handlers?

public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Application.Inspectors.NewInspector += Inspectors_NewInspector;
    }

    void Inspectors_NewInspector(Outlook.Inspector Inspector)
    {
        Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
        if (mailItem != null)
        {
            if (mailItem.EntryID == null)
            {
                mailItem.BeforeAttachmentAdd += mailItem_BeforeAttachmentAdd;
                //System.Windows.Forms.MessageBox.Show("Twice");
            }
        }
    }

    void mailItem_BeforeAttachmentAdd(Outlook.Attachment Attachment, ref bool Cancel)
    {
        Cancel = true;
    }

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

Solution

  • The COM object that raises the events must be alive. In your case you are using multiple dot notation and the compiler creates an implicit variable; once that variable is garbage collected, it will stop firing events. Ditto for the mail items - you will need to trap the inspector.Close event and remove the items from the _mailItems list;

    public partial class ThisAddIn
    {
        private Inspectors _inspectors;
        private List<MailItem> _mailItems = new List<MailItem>();
    
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            _inspectors = Application.Inspectors;
            _inspectors.NewInspector += Inspectors_NewInspector;
        }
    
        void Inspectors_NewInspector(Outlook.Inspector Inspector)
        {
            Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
            if (mailItem != null)
            {
                if (mailItem.EntryID == null)
                {
                    _mailItems.Add(mailItem):
                    mailItem.BeforeAttachmentAdd += mailItem_BeforeAttachmentAdd;
                    //System.Windows.Forms.MessageBox.Show("Twice");
                }
            }
        }
    
        void mailItem_BeforeAttachmentAdd(Outlook.Attachment Attachment, ref bool Cancel)
        {
            Cancel = true;
        }
    
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }