VSTO Outlook插件:捕获发送事件及内联项识别问题
解决VSTO Outlook插件ItemSend事件与内联邮件类型识别问题
一、确保ItemSend事件稳定绑定
你初期遇到主界面内联发送时事件未触发,大概率是事件委托被垃圾回收导致的。要在ThisAddIn类中声明全局级别的委托变量,避免局部变量被GC回收:
private Outlook.ApplicationEvents_11_ItemSendEventHandler _itemSendHandler; private void ThisAddIn_Startup(object sender, System.EventArgs e) { _itemSendHandler = new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend); Application.ItemSend += _itemSendHandler; } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { // 解绑事件避免内存泄漏 if (_itemSendHandler != null) { Application.ItemSend -= _itemSendHandler; } }
二、正确识别内联邮件类型
不要依赖Application.ActiveWindow().CurrentItem判断类型,内联发送时ActiveWindow是Explorer窗口,其CurrentItem无法准确指向正在发送的内联邮件。直接使用ItemSend事件传入的Item参数,这是Outlook直接传递的待发送对象,完全可靠:
private void Application_ItemSend(object Item, ref bool Cancel) { // 直接判断传入对象的类型 if (Item is Outlook.MailItem mailItem) { var result = MessageBox.Show($"即将发送邮件:{mailItem.Subject}", "发送警告", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { Cancel = true; // 取消发送操作 } } // 可扩展处理其他发送项(如会议请求) else if (Item is Outlook.AppointmentItem apptItem) { // 会议请求发送逻辑 } }
三、区分内联/独立窗口发送(可选)
如果需要区分两种发送场景,可通过邮件的Inspector属性判断:
private void Application_ItemSend(object Item, ref bool Cancel) { if (Item is Outlook.MailItem mailItem) { using (Outlook.Inspector inspector = mailItem.GetInspector) { // 内联发送时,Inspector通常不可见或处于最小化状态 if (!inspector.Visible || inspector.WindowState == Outlook.OlWindowState.olMinimized) { MessageBox.Show("当前为内联发送模式", "发送警告"); } else { MessageBox.Show("当前为独立窗口发送模式", "发送警告"); } } } }
注意:使用Outlook COM对象后需及时释放,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Y.T
相关产品推荐
相关产品推荐

