事件处理程序未添加到新的邮件项目 [英] Event Handler not being added to new Mail Items

查看:167
本文介绍了事件处理程序未添加到新的邮件项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个响应新的附件事件的简单的Outlook 2010加载项。
以下代码仅在我取消注释MessageBox.Show行时有效。但是删除它似乎不添加事件处理程序。我缺少程序流程,意味着模态消息框会影响事件处理程序的位置?

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


推荐答案

引发事件的COM对象必须存活。在你的情况下,你使用多个点符号,编译器创建一个隐式变量;一旦该变量被垃圾回收,它将停止触发事件。同样的邮件项目 - 您将需要捕获检查员。关闭事件并从_mailItems列表中删除项目;

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

这篇关于事件处理程序未添加到新的邮件项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆