Outlook 2013 VSTO - 不会触发当前资源管理器的事件

Outlook 2013 VSTO - Events for current explorer are not fired

Explorer 对象的事件未触发的可能原因是什么?我正在使用下面的简单代码,只是为所有 Explorer 对象注册事件。我总是在调试 window 中得到 Init new Explorer! 行一次,所以有一个 Explorer 对象。然后当我在 Outlook 中四处点击,从邮件切换到日历视图,select 项目,切换回来,切换到联系人,......我只得到一些(!)第一个事件,不确定是哪个事件。几秒钟后,尽管不断单击和更改视图,但我没有再收到任何事件。这里有什么问题?

private void ThisAddInStartup(object sender, System.EventArgs e)
{
    foreach (var exp in this.Application.Explorers)
    {
        this.ExplorersOnNewExplorer(exp as Explorer);
    }
    this.Application.Explorers.NewExplorer += this.ExplorersOnNewExplorer;
}

private void ExplorersOnNewExplorer(Explorer currentExplorer)
{
    Debug.WriteLine("Init new Explorer!");

    currentExplorer.BeforeViewSwitch += this.CurrentExplorerOnBeforeViewSwitch;
    currentExplorer.BeforeFolderSwitch += this.CurrentExplorerOnBeforeFolderSwitch;
    currentExplorer.SelectionChange += this.CurrentExplorerOnSelectionChange;
    currentExplorer.ViewSwitch += this.CurrentExplorerOnFolderSwitch;
    currentExplorer.FolderSwitch += this.CurrentExplorerOnFolderSwitch;
}
private void CurrentExplorerOnBeforeFolderSwitch(object newFolder, ref bool cancel)
{
    Debug.WriteLine("BeforeFolderSwitch!");
}

private void CurrentExplorerOnBeforeViewSwitch(object newView, ref bool cancel)
{
    Debug.WriteLine("BeforeViewSwitch!");
}

private void CurrentExplorerOnFolderSwitch()
{
    Debug.WriteLine("CurrentExplorerOnFolderOrViewSwitch!");
}

private void CurrentExplorerOnSelectionChange()
{
    Debug.WriteLine("Selection changed!");
}

触发事件的对象必须保持活动状态。在您的情况下,您在作为参数传递的对象上设置了事件处理程序。一旦超出范围,它就会被释放,并且不会触发任何事件。 Explorer 和 Explorer 都必须在 class 级别声明。

您可能还想跟踪 Explorer.Close 事件以从您正在监视的对象列表中删除 Explorer 对象。

private List<Explorer> _explorers = new List<Explorer>();
private Explorer explorer;
private void ThisAddInStartup(object sender, System.EventArgs e)
{
    _explorers = this.Application.Explorers;
    foreach (var exp in _explorers)
    {
        this.ExplorersOnNewExplorer(exp as Explorer);
    }
    _explorers.NewExplorer += this.ExplorersOnNewExplorer;
}

private void ExplorersOnNewExplorer(Explorer currentExplorer)
{
    _explorers.Add(currentExplorer);
    Debug.WriteLine("Init new Explorer!");

    currentExplorer.BeforeViewSwitch += this.CurrentExplorerOnBeforeViewSwitch;
    currentExplorer.BeforeFolderSwitch += this.CurrentExplorerOnBeforeFolderSwitch;
    currentExplorer.SelectionChange += this.CurrentExplorerOnSelectionChange;
    currentExplorer.ViewSwitch += this.CurrentExplorerOnFolderSwitch;
    currentExplorer.FolderSwitch += this.CurrentExplorerOnFolderSwitch;
}