Explorer
对象发生事件的原因可能是什么?我正在使用下面的简单代码,只是为所有Explorer
个对象注册事件。我总是在调试窗口中获取Init new Explorer!
行一次,因此有一个Explorer
对象。当我在Outlook中单击时,从邮件切换到日历视图,选择项目,切换回,切换到联系人,...我只得到一些(!)的第一个事件,而不是确定性的哪个事件。几秒钟之后,尽管仍然保持点击和更改视图,但我没有获得更多活动。这有什么不对?
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!");
}
答案 0 :(得分:5)
触发事件的对象必须保持活动状态。在您的情况下,您在作为参数传递的对象上设置事件处理程序。一旦超出范围,它就会被释放,并且不会发生任何事件。必须在课程级别声明Explorers和Explorer。
您可能还想跟踪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;
}