public IList<IVsHierarchy> GetSelectedNodes()
{
// Retrieve shell interface in order to get current selection
IVsMonitorSelection monitorSelection = GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
if(monitorSelection == null)
{
throw new InvalidOperationException();
}
List<IVsHierarchy> selectedNodes = new List<IVsHierarchy>();
IntPtr hierarchyPtr = IntPtr.Zero;
IntPtr selectionContainer = IntPtr.Zero;
try
{
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierarchies, hierarchyPtr is Zero
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
// We only care if there are one ore more nodes selected in the tree
if(itemid != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero)
{
IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
if(itemid != VSConstants.VSITEMID_SELECTION)
selectedNodes.Add(hierarchy);
else if(multiItemSelect != null)
{
// This is a multiple item selection.
//Get number of items selected and also determine if the items are located in more than one hierarchy
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
bool isSingleHierarchy = (isSingleHierarchyInt != 0);
// Now loop all selected items and add to the list only those that are selected within this hierarchy
Debug.Assert(numberOfSelectedItems > 0, "Bad number of selected itemd");
VSITEMSELECTION[] vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems];
uint flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections));
foreach (VSITEMSELECTION vsItemSelection in vsItemSelections)
{
IVsHierarchy node = vsItemSelection.pHier;
if(node != null)
selectedNodes.Add(node);
}
}
}
}
finally
{
if(hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if(selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
return selectedNodes;
}