Event Handler not being added to new Mail Items

眉间皱痕 提交于 2019-12-31 04:32:12

问题


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)
    {
    }

回答1:


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)
    {
    }


来源:https://stackoverflow.com/questions/24576890/event-handler-not-being-added-to-new-mail-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!