VSIP: ITrackSelection
Yesterday I was trying to access to the service
STrackSelection (in order to change the selection in
visual studio), I was very confused because in some cases
the GetService failed.
For example when I requested the service in the package
initialize the getservice failed.
protected class MyPackage : Package
override
void Initialize()
{ base.Initialize();
ITrackSelection track = (ITrackSelection)
GetService(typeof(STrackSelection));
}
However If I implement a tool window and call the
GetService on the service provider of the toolwindow the
GetService call succeed
This behavior was very well explained by Douglas
Hodges (Microsoft):
“...ITrackSelection or IVsTrackSelectionEx (“SID_STrackSelection” or “SID_SVsTrackSelectionEx” respectively) are only available from the
IServiceProvider that is implemented on the site object of
a WindowFrame. Basically selection is tracked on a
per-window basis. The site pointer that is used to site
the IVsWindowPane object provides these TrackSelection
services. You can not get these services from the global
IServiceProvider that is passed to your IVsPackage object.
So the easiest thing is when you are the IVsWindowPane
object sited in an IVsWindowFrame, then you are passed the
IServiceProvider to use as part of IVsWindowPane::SetSite.
If you are not this object, you can still get to the
IServiceProvider of an IVsWindowFrame by calling
IVsWindowFrame::GetProperty(VSFPROPID_SPFrame, …).
Remember you can only set the selection on a window; there
is no notion of a global selection context. Each
WindowFrame remembers its selection. When the window is
activated, its selection is pushed to the global
IVsMonitorSelection service that is used by anyone to get
events when the selection changes.”