0

我正在努力捕捉 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        
4

1 回答 1

0

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

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

于 2021-03-02T21:49:11.027 回答