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);
}
3
  • 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 2, 2012 at 17:35
  • For my own information: Where are you binding to OnConnection and OnStartupComplete? What object has these events? Sep 20, 2015 at 16:05
  • I don't think they are events, they are the public methods of the interface IExtensibility2
    – Matt
    Sep 21, 2015 at 8:57

1 Answer 1

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.

1
  • 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 5, 2012 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.