protected internal virtual IList<HierarchyNode> GetSelectedNodes()
{
// Retrieve shell interface in order to get current selection
IVsMonitorSelection monitorSelection = this.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
if (monitorSelection == null)
{
throw new InvalidOperationException();
}
List<HierarchyNode> selectedNodes = new List<HierarchyNode>();
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 hierachies, 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)
{
// This is a single selection. Compare hirarchy with our hierarchy and get node from itemid
if (Utilities.IsSameComObject(this, hierarchy))
{
HierarchyNode node = this.NodeFromItemId(itemid);
if (node != null)
{
selectedNodes.Add(node);
}
}
else
{
NestedProjectNode node = this.GetNestedProjectForHierarchy(hierarchy);
if (node != null)
{
selectedNodes.Add(node);
}
}
}
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
if (!isSingleHierarchy || (isSingleHierarchy && Utilities.IsSameComObject(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)
{
if (isSingleHierarchy || Utilities.IsSameComObject(this, vsItemSelection.pHier))
{
HierarchyNode node = this.NodeFromItemId(vsItemSelection.itemid);
if (node != null)
{
selectedNodes.Add(node);
}
}
}
}
}
}
}
finally
{
if (hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
return selectedNodes;
}