首页 文章

VSTO ItemAdd 事件未触发

提问于
浏览
0

我有以下 VSTO add-in 代码。但是,items_ItemAdd()方法不会被卷入。

public partial class ThisAddIn
    {
        Outlook.NameSpace outlookNameSpace;
        Outlook.MAPIFolder inbox;
        Outlook.Items items;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            outlookNameSpace = this.Application.GetNamespace("MAPI");
            Debug.WriteLine("Starting Add-In");
            inbox = outlookNameSpace.GetDefaultFolder(
                    Microsoft.Office.Interop.Outlook.
                    OlDefaultFolders.olFolderInbox);
            items = inbox.Items;
            items.ItemAdd +=
                new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
            Debug.WriteLine("Started Add-In");
        }

        void items_ItemAdd(object Item)
        {
            Debug.WriteLine("New email arrived.");
            Outlook.MailItem mail = (Outlook.MailItem)Item;
            if (Item != null)
            {
                if (mail.MessageClass == "IPM.Note")
                {
                    string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "example.html");
                    Debug.WriteLine("Saving to " + path);
                    mail.SaveAs(path, Outlook.OlSaveAsType.olHTML);
                }
            }
        }

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

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }

这与MSDN中给出的示例非常相似。有人有想法吗?我正在使用 VSTO Outlook 2007 add-in 在 Visual Studio 2010 中进行开发。在调试模式下尝试此操作,但事件未触发。我的开发机上安装了 Outlook 2010。

1 回答

  • 0

    尽管声明了一些班级成员绕过垃圾收集,但我无法使ItemsEvents_ItemAddEventHandler正常工作,因为这似乎是互联网上到处建议的唯一答案...

    起作用的方法是在附加事件时增加一点时间延迟,如下所示:

    System.Threading.Timer timer = null;
    timer = new System.Threading.Timer((obj) =>
    {
        ItemAddEventHandler();
        timer.Dispose();
    }, null, 3000, System.Threading.Timeout.Infinite);
    

    我确实发现NewMailEx事件更可靠,但是它有一些缺点,例如无法选择要收听事件_2 的文件夹,这对某人有帮助,尽管从任何角度来看这都不是一个干净的解决方案。

相关问题