user6189
user6189

Reputation: 673

Visual Studio Extension: Track when new code window is opened?

I'm trying to write a Visual Studio Extension that tracks when a new code window is opened. I found a class IVsCodeWindowEvents that seems to provide listener methods for that:

public int OnNewView(IVsTextView pView)

However, I have a problem that I don't know how to register to listen to these events.

My class looks like this:

public sealed class VSTrackerPackage : Package, IVsCodeWindowEvents

In this class, I implement the OnNewView method, but how can I register this listener in my Initialize method?

Upvotes: 2

Views: 122

Answers (1)

Philip Pittle
Philip Pittle

Reputation: 12295

Yes you can register for Visual Studio events via the DTE and more specifically DTE2.

First step is to get access from your Package via the Initialize method:

public sealed class VSTrackerPackage : Package
{
    DTE2 dte = GetService(typeof (DTE)) as DTE2;
}

At this point, I'd recommend attaching to the DocumentEvents.DocumentOpened event. From there you can check if it's a document you are interested in or not. You can also get the Window if you need to interact with it there:

_dte.Events.DocumentEvents.DocumentOpened += document =>
        {
            //double check this logic.
            if (document.Language != "C#")
                return;

            //do work


            //or - load window document.ActiveWindow.
        };

If it helps, I have an open source Visual Studio plugin (shameluss plug: pMixins ) that attaches to a number of VS events. Relevant class is on GitHub: https://github.com/ppittle/pMixins/blob/master/CopaceticSoftware.CodeGenerator.StarterKit/Infrastructure/VisualStudioEventProxy.cs. Class definition starts on line 243.

Upvotes: 1

Related Questions