我正在尝试创建一个响应新附件事件的简单Outlook 2010加载项。 下面的代码仅在我取消注释MessageBox.Show行时才有效。但删除它似乎不添加事件处理程序。我对程序流的缺失是什么意味着模态消息框会影响事件处理程序的位置?
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Application.Inspectors.NewInspector += Inspectors_NewInspector;
}
void Inspectors_NewInspector(Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
mailItem.BeforeAttachmentAdd += mailItem_BeforeAttachmentAdd;
//System.Windows.Forms.MessageBox.Show("Twice");
}
}
}
void mailItem_BeforeAttachmentAdd(Outlook.Attachment Attachment, ref bool Cancel)
{
Cancel = true;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
答案 0 :(得分:5)
引发事件的COM对象必须处于活动状态。在您的情况下,您使用多点符号,编译器创建一个隐式变量;一旦该变量被垃圾收集,它将停止触发事件。同样适用于邮件 - 您需要捕获inspector.Close事件并从_mailItems列表中删除项目;
public partial class ThisAddIn
{
private Inspectors _inspectors;
private List<MailItem> _mailItems = new List<MailItem>();
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
_inspectors = Application.Inspectors;
_inspectors.NewInspector += Inspectors_NewInspector;
}
void Inspectors_NewInspector(Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
_mailItems.Add(mailItem):
mailItem.BeforeAttachmentAdd += mailItem_BeforeAttachmentAdd;
//System.Windows.Forms.MessageBox.Show("Twice");
}
}
}
void mailItem_BeforeAttachmentAdd(Outlook.Attachment Attachment, ref bool Cancel)
{
Cancel = true;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}