我正在使用C#和Visual Studio2010开发我的第一个Outlook2010插件。到目前为止,我的项目进展顺利。我在功能区中有一个自定义选项卡,每次在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();发布于 2013-01-17 21:46:56
使用COM对象时:当您想要订阅一个事件时,您必须在类/应用程序级别保留对该对象的引用,否则它将在超出作用域时被垃圾回收。
https://stackoverflow.com/questions/14369102
复制相似问题