10

While trying to develop my first VS Addin, I am having issues in firing DTE2 events.

Basically, the DocumentOpened and LineChanged events don't fire for some reason. What important part did I miss?

namespace TestAddin {
  public class Connect : IDTExtensibility2 {
    private AddIn _addInInstance;
    private DTE2 _applicationObject;

    public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) {
      _applicationObject = (DTE2) application;
      _addInInstance = (AddIn) addInInst;

      _applicationObject.Events.DocumentEvents.DocumentOpened += InitializeFoldingOnDocument;
      _applicationObject.Events.TextEditorEvents.LineChanged += UpdateFoldingOnDocument;
    }

    private void UpdateFoldingOnDocument(TextPoint startpoint, TextPoint endpoint, int hint) {
      RegionFolding(_applicationObject.ActiveDocument);
    }

    private void InitializeFoldingOnDocument(Document document) {
      RegionFolding(document);
    }

    private void RegionFolding(Document _document) {
      // Do the folding [...]
    }

    // Other IDTExtensibility2 Members [...]
  }
}
Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
fjdumont
  • 1,517
  • 1
  • 9
  • 22

2 Answers2

22

You need to save the DocumentEvents class. I think they will be disposed or garbage collected else.

In my case.

private SolutionEvents solutionEvents;

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    Globals.DTE = (DTE2)application;
    Globals.Addin = (AddIn)addInInst;

    solutionEvents = Globals.DTE.Events.SolutionEvents;
    solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(SolutionEvents_Opened);
    solutionEvents.BeforeClosing += new _dispSolutionEvents_BeforeClosingEventHandler(SolutionEvents_BeforeClosing);
}
Twenty
  • 5,234
  • 4
  • 32
  • 67
ptomasroos
  • 1,129
  • 1
  • 9
  • 18
  • 1
    Being a novice VSX developer here, this one got me pretty good. If anyone's interested here's the Microsoft KB problem article on the subject: http://support.microsoft.com/kb/555430 – Dan Nolan Jul 18 '11 at 07:56
  • I don't know how you figured this out but this is brilliant! – justin.m.chase Sep 10 '11 at 17:21
0

I found a different solution to this problem.

I was boxing and unboxing my DTE object before doing my event subscriptions. This ulitmately proved the culprit for me. While this wasn't your issue, it could help others who have similar issues; and is good to know so that you don't make the same mistakes I did which took an extreme amount of time to resolve.

See here: http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/eb1e8fd1-32ad-498c-98e9-25ee3da71004

Dessus
  • 2,147
  • 1
  • 14
  • 24