I have been trying to add a command filter to all text editors in Visual Studio for a project, since I had to collect information from several number of sources I wanted to collect them in one place in the hope that somebody else might find it useful.

In order to get notification when a text view is registered in Visual Studio, we first have to register an implementation of IVsTextManagerEvents as an event sink. In order to do this you can use the following code block which uses IVsTextManager service.

IVsTextManager textManager = this.GetService(typeof(SVsTextManager)) as IVsTextManager;
IConnectionPointContainer container = textManager as IConnectionPointContainer;
IConnectionPoint textManagerEventsConnection = null;
Guid eventGuid = typeof(IVsTextManagerEvents).GUID;
container.FindConnectionPoint(
ref eventGuid, out textManagerEventsConnection);
uint cookie = 0;
textManagerEventsConnection.Advise(
this, out cookie);

Now IVsTextManagerEvents.OnRegisterView method is going to be called for each new view created. In that method you can use passed IVsTextView.AddCommandFilter method to add a command filter. However, when the event is raised the window is actually not initialized fully so any command filter you add will be below the language service filters thus you won't see all of the commands. My solution to this problem was to check the text buffer each time Exec method was called on the filter and remove/add the filter once the buffer wasn't empty anymore. I am still trying to find a better solution and I will update this entry if I find anything better than relying on the buffer. One apparent problem with this solution is that as long as the text view remains empty, the filter will not be re-registered thus causing you to lose some events on empty files.