What could be possible reasons for the events of the Explorer
object not firing? I am using the simple code below, just registering the events for all Explorer
objects. I always get the Init new Explorer!
line in debug window once, so there is one Explorer
object. When I then click around in Outlook, switch from mail to calendar view, select items, switch back, switch to contacts, ... I get only some (!) of the first events, not deterministic which event. And after some seconds, I get no more events despite keeping clicking and changing views. What's wrong here?
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!");
}
The object that fires the events must be kept alive. In your case you set up event handlers on the object that is passed as a parameter. As soon as it goes out of scope, it is released, and no events will fire. Both Explorers and Explorer must be declared on the class level.
You might also want to track the Explorer.Close event to remove the Explorer object from the list of object you are watching.
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;
}