未触发Outlook ItemAdd事件

时间:2014-05-22 10:16:37

标签: c# office-interop outlook-addin

我们编写了一个Outlook加载项,可以在发送电子邮件时启动操作。只有在撰写电子邮件期间设置了标志时才会发生此操作。通过单击切换按钮设置标志。当发送电子邮件时,会触发事件,并将电子邮件的ID存储在队列中。如果邮件出现在已发送文件夹中,则应触发事件,如果队列中发现相同的ID,则应执行操作。

下面我有两种方法。在发送电子邮件时将发生Application_ItemSend,并且在该方法中,在SentItemsQueue上调用EnQueue。 EnQueue方法将事件附加到已发送邮件文件夹,当添加项目时,它应触发将开始我们操作的事件。

当组合电子邮件并在Outlook中发送时,这一切都正常。如果我们从外部程序(如Word)中启动电子邮件,则会执行Application_ItemSend,但不会触发EMailFoundInSentItems(附加在EnQueue中)。为什么事件永远不会被触发?

public partial class ThisAddIn {    

  void Application_ItemSend(object item, ref bool cancel)
    {
       try
       {
         Trace.TraceInformation("E-mail is being sent. Checking for archive flag.");
         MailItem mail = item as MailItem;
         bool? archive = mail.GetArchiveFlag();

         if (archive == true)
         {
           Trace.TraceInformation("Archive flag was set, going to queue e-mail for archiving.");
           this.SentItemsQueue.EnQueue(mail);
         }

         Marshal.ReleaseComObject(mail);
       }
       catch (System.Exception ex)
       {
         Trace.TraceError("An exception was thrown while trying to archive a sent mail item. Exception: {0}.", ex.ToString());
       }
    }
...

public class SentItemsArchiveQueue 
{
  public void EnQueue(MailItem mail)
    {
      // remove and re-add handler (remove first, so it's not registered twice)
      mail.SaveSentMessageFolder.Items.ItemAdd -= new ItemsEvents_ItemAddEventHandler(EMailFoundInSentItems);
      mail.SaveSentMessageFolder.Items.ItemAdd += new ItemsEvents_ItemAddEventHandler(EMailFoundInSentItems);

      this.Queue.Add(mail.ConversationIndex);
      Trace.TraceInformation("Queue ConversationIndex is {0}", mail.ConversationIndex);
    }
...

1 个答案:

答案 0 :(得分:6)

引发事件(Items集合)的对象必须保持活动才能引发事件。您正在使用多点符号,一旦编译器创建的隐式变量超出范围并被垃圾收集,就不会引发任何事件:

public class SentItemsArchiveQueue 
{
  Items _items;

  public void EnQueue(MailItem mail)
    {
      _items = mail.SaveSentMessageFolder.Items;
      _items.ItemAdd += new ItemsEvents_ItemAddEventHandler(EMailFoundInSentItems);

      this.Queue.Add(mail.ConversationIndex);
      Trace.TraceInformation("Queue ConversationIndex is {0}", mail.ConversationIndex);
    }