5

For some reason in my app my FolderSwitch works on the main Explorer that opens with the application but the NewExplorer event never fires, so obviously the FolderSwitch event won't fire on a new Explorer.

I can't work out why the event doesn't fire.

private List<_Outlook.Explorer> ListOfExplorerWindows = new List<_Outlook.Explorer> { };
private _Outlook.Application Application;

public void OnConnection(object Application, Extensibility.ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
    this.Application = (_Outlook.Application)Application;
}

public void OnStartupComplete(ref Array custom)
{
    _Outlook.Explorer Explorer = this.Application.ActiveExplorer();
    Explorer.FolderSwitch += new _Outlook.ExplorerEvents_10_FolderSwitchEventHandler(Explorer_FolderSwitch);
    ListOfExplorerWindows.Add(Explorer);

    this.Application.Explorers.NewExplorer += new _Outlook.ExplorersEvents_NewExplorerEventHandler(Explorers_NewExplorer);
}

private void Explorers_NewExplorer(_Outlook.Explorer Explorer)
{
    Explorer.FolderSwitch += new _Outlook.ExplorerEvents_10_FolderSwitchEventHandler(Explorer_FolderSwitch);
    ListOfExplorerWindows.Add(Explorer);
}
Matt
  • 1,436
  • 12
  • 24
  • Actually, I may have fixed it by adding private _Outlook.Explorers Explorers; at class level, however I thought private _Outlook.Application Application; would keep it in scope, can anyone explain? – Matt Mar 02 '12 at 17:35
  • For my own information: Where are you binding to OnConnection and OnStartupComplete? What object has these events? – Scott Baker Sep 20 '15 at 16:05
  • I don't think they are events, they are the public methods of the interface IExtensibility2 – Matt Sep 21 '15 at 08:57

1 Answers1

6

For any events you want to keep around when using VSTO, you are required to keep around a class-level member (Explorer, Application, Inspector, CommandBar, etc.) to keep the GC Thread from removing them. This is a resource optimization, but can also be a painful lesson to learn.

See related MSDN Forum post regarding event lifetime or similar SO post.

Community
  • 1
  • 1
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
  • Yes but I have "private _Outlook.Application Application;" which is a class level object of Application, however this doesn't seem to be enough, that's what I don't understand. Does my Application.Explorers get collected by the GC even though Application is declared at Class level? – Matt Mar 05 '12 at 10:58