事件绑定并不总是在Outlook加载项启动期间发生

本文关键字:启动 加载项 Outlook 绑定 事件 | 更新日期: 2023-09-27 17:53:57

我正在使用c#和Visual Studio 2010开发我的第一个Outlook 2010插件。到目前为止,我的项目进展顺利。我在功能区中有一个自定义选项卡,每次在outlook窗口中选择新消息时,它都会更新。分析电子邮件中的文本,并在功能区中显示不同的信息。

是什么让这一切的工作是在我的ThisAddIn_Startup方法。在这里,我绑定了一些Outlook事件,这样我的代码就可以在选择新邮件时做出相应的反应。

真正令人不安的是,这是间歇性失败大约1/3的时间。我们公司有几个来自不同厂商的outlook插件,所以很难确切地知道outlook启动过程中发生了什么。有时我的代码绑定到Outlook的事件,有时不绑定。如果不能,我关闭并重新打开Outlook,它就能工作了。任何建议都将不胜感激。有什么更好的办法吗?如果我不得不预料到这些间歇性的启动失败,有什么办法让我的插件意识到这一点,并在不需要重新启动应用程序的情况下恢复吗?

下面是我在ThisAddIn.cs中的代码示例:

private void ThisAddIn_Startup(object sender, System.EventArgs e) {
    // set up event handler to catch when a new explorer (message browser) is instantiated
    Application.Explorers.NewExplorer += new Microsoft.Office.Interop.Outlook.ExplorersEvents_NewExplorerEventHandler(NewExplorerEventHandler);
    // ...and catch any Explorers already existing before this startup event was fired
    foreach (Outlook.Explorer Exp in Application.Explorers) {
        NewExplorerEventHandler(Exp);
    }
}
public void NewExplorerEventHandler(Microsoft.Office.Interop.Outlook.Explorer Explorer) {
    if (Explorer != null) {
        //set up event handler so our add-in can respond when a new item is selected in the Outlook explorer window
        Explorer.SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(ExplorerSelectionChange);
    }
}
private void ExplorerSelectionChange() {
    Outlook.Explorer ActiveExplorer = this.Application.ActiveExplorer();
    if (ActiveExplorer == null) { return; }
    Outlook.Selection selection = ActiveExplorer.Selection;
    Ribbon1 ThisAddInRibbon = Globals.Ribbons[ActiveExplorer].Ribbon1;
    if (ThisAddInRibbon != null) {
        if (selection != null && selection.Count == 1 && selection[1] is Outlook.MailItem) {
            // one Mail object is selected
            Outlook.MailItem selectedMail = selection[1] as Outlook.MailItem; // (collection is 1-indexed)
            // tell the ribbon what our currently selected email is by setting this custom property, and run code against it
            ThisAddInRibbon.CurrentEmail = selectedMail;
        } else {
            ThisAddInRibbon.CurrentEmail = null;
        }
    }
}

更新:我在ThisAddIn类中添加了两个变量,用于捕获两个对象的事件:

Outlook.Explorers _explorers; // used for NewExplorerEventHandler
Outlook.Explorer _activeExplorer; // used for ExplorerSelectionChange event
在ThisAddIn_Startup:

_explorers = Application.Explorers;
_explorers.NewExplorer += new Microsoft.Office.Interop.Outlook.ExplorersEvents_NewExplorerEventHandler(NewExplorerEventHandler);
在ExplorerSelectionChange:

_activeExplorer = this.Application.ActiveExplorer();

事件绑定并不总是在Outlook加载项启动期间发生

使用COM对象时:当你想订阅一个事件时,你必须在类/应用程序级别保持对该对象的引用,否则在超出作用域时它将被垃圾收集