C# Outlook VSTO - BeforeAttachmentAdd 有时只是没有被解雇

C# Outlook VSTO - BeforeAttachmentAdd sometimes is just not fired

我正在努力捕捉 BeforeAttachmentAdd 事件。 有时候就是不触发,不知道为什么。

没有异常,事件已正确注册,但在添加附件之前未触发。 我试图找出它何时被触发以及何时不被触发 - 运气不好。对我来说似乎完全随机。

这是我的代码:

     private Outlook.Application application;
     private Outlook.Inspectors inspectors;
     private Outlook.Explorer explorer;

     private void NGAddIn_Startup(object sender, System.EventArgs e)
     {
         this.application = Globals.NGAddIn.Application;
         this.inspectors = this.application.Inspectors;
         this.explorer = application.Explorers.Application.ActiveExplorer();
        
         this.inspectors.NewInspector += NewMailInspector;
     }

     internal static void NewMailInspector(Outlook.Inspector inspector)
     {
         bool isProtectAttachmentEnabled = Properties.Settings.Default.ProtectedAttachment_isEnabled;
         
         Outlook.MailItem mailItem = inspector.CurrentItem as Outlook.MailItem;
         if (isProtectAttachmentEnabled && mailItem != null)
         {
             mailItem.BeforeAttachmentAdd += BeforeAttachmentInspector;                
         }
     }

     private static void BeforeAttachmentInspector(Outlook.Attachment attachment, ref bool cancel)
     {
         Outlook.MailItem mailItem = attachment.Parent;            

         if (attachment.Parent is Outlook.MailItem)
         {
             FormPassword formPassword = new FormPassword();

             if (formPassword.ShowDialog() == DialogResult.OK)
             {
                 string zipFilePath = Zipper.ZipAndProtectAttachment(attachment, formPassword.Password);

                 mailItem.Attachments.Remove(mailItem.Attachments.Count);
                 mailItem.Attachments.Add(zipFilePath);
             }
         }
     }

     private void NGAddIn_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(NGAddIn_Startup);
         this.Shutdown += new System.EventHandler(NGAddIn_Shutdown);
     }

     #endregion        

引发事件的对象 (mailItem) 是一个局部变量,可以在 NewMailInspector 方法退出后随时由垃圾收集器释放。之后不会引发任何事件。

创建一个 class 包装 Inspector 对象并使 mailItem 成为其成员。请注意,在您的插件主 class 中将 mailItem 设置为全局(class)变量并不是一个好主意,因为您可以打开多条消息。