没有 Visual Studio,MailItem 事件不会触发

MailItem event not firing without Visual Studio

我想处理来自 Outlook 邮件项的 BeforeAttachmentAdd 事件。但是我的代码在 Visual Studio 环境中工作但不工作。你有想法吗?

这是我的代码:

namespace MyOutlookProject
{
   using Microsoft.Office.Interop.Outlook;
   using OutlookApplication = Microsoft.Office.Interop.Outlook.Application;
   using OutlookAttachment = Microsoft.Office.Interop.Outlook.Attachment;
   using OutlookInspector = Microsoft.Office.Interop.Outlook.Inspector;
   using OutlookMail = Microsoft.Office.Interop.Outlook.MailItem;
   class MailManager
   {
      public void StartUp(OutlookApplication application)
      {
         _inspectors = application.Inspectors;
         _inspectors.NewInspector += Inspectors_NewInspector;
      }

      private void Inspectors_NewInspector(OutlookInspector Inspector)
      {
         if (Inspector.CurrentItem is OutlookMail)
         {
            OutlookMail mail = (Inspector.CurrentItem as OutlookMail);
            mail.BeforeAttachmentAdd += Mail_BeforeAttachmentAdd;
         }
      }

      private void Mail_BeforeAttachmentAdd(OutlookAttachment Attachment, ref bool Cancel)
      {
         /*Never called without Visual Studio*/
      }
   }
}

感谢您的帮助。

据我所知,您可能遇到了我的按钮停止工作的问题 摘自 E. Carter 和 E. Lippert 的书 VSTO 2007

上面写着

One issue commonly encountered when beginning to program agains Office events in .NET is known as the "my button stopped working" issue. A developer will write some code to handle a Click event raised by a CommandBarButton in the Office toolbar object model. This code will sometimes work temporarily but then stop. The user will click the button, but the Click event appears to have stopped working. The cause of this issue is connecting an event handler to an object whose lifetime does not match the desired lifetime of the event. This tipcally occurs when the object to which you are connecting an event handler goes out of scope or gets sets to null so that it gets garbage collected.

我认为在您的情况下,OulookMail 类型的 .NET RCW object 使用变量 mail 进行操作是罪魁祸首。它的生命周期没有得到妥善处理。在 Visual Studio 中不会发生这种情况的事实是,您可能处于调试模式,该模式会稍微更改垃圾收集,因此在您进行测试时您的对象尚未被销毁。

触发事件的对象(代码中的 mail 变量)必须处于 global/class 级别,以防止其被垃圾收集。在你的情况下变量是本地的。

一般来说,您可以打开多个检查器,因此拥有一个包含对检查器及其邮件项目的引用的包装器对象,并在您的插件中包含此类包装器的列表可能是有意义的。