IVsMonitorSelection

The functionality of IVsMonitorSelection is described in the VSIP documentation as “Enabling VSPackages to receive notification of selection events and to retrieve information about the current project hierarchy, item, element value, and command UI context.”

Who implements this interface?

IVsMonitorSelection is implemented by the Visual Studio shell. You can get to an implementer of IVsMonitorSelection by doing a GetService/QueryService for SVsMonitorSelection. [If you’ve been working with VSIP for a while, you’ve certainly noticed this pattern: ask for a service, cast to an interface.] In C# it looks like this:

IVsMonitorSelection monitorSelectionService = (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection));

Now you should be able to call the various methods defined by IVsMonitorSelection on the object that is returned.
 
What does this interface let me do?

According to the VSIP 2003 Extras documentation, this interface allows a package to “register for selection event notification, to cancel the registration, to retrieve current selections and element values, and to manage command UI context information”

To restate the above, the interface allows you to do 2 basic things:

  1. Get and set information about the active UI contexts (NoSolution, Debugging, DesignMode, etc….). UI Context is most often used as a way for a package to control the visibility of its commands without actually being loaded. If (for whatever reason) you decide you need to find out about the active context after your package is loaded, you can easily do this with GetCmdUIContextCookie & IsCmdUIContextActive. If you want to set an existing or new context, you can call SetCmdUIContext. A context is simply a GUID that you can define and activate/deactivate as needed for your package. Visual Studio has some pre-defined contexts/GUIDs that it manages (e.g. NoSolution, SolutionExists, etc…) . You can find the GUIDs for these pre-defined contexts in the Visual Studio SDK documentation.
  2. Get selection information. You can use (Un)AdviseSelectionEvents to be notified (or no longer notified) about changes in the current user’s selection. This is helpful when you need to change what you’re displaying or how a command/toolwindow behaves depending on where the user focus is. GetCurrentSelection & GetCurrentElementValue can be used to get the current selection object (e.g. the active project item in Solution Explorer) and other information about the current selection.