In a VS 2015 extension, how can I get the selected

2019-07-04 15:53发布

问题:

I'm interested in getting a Project or ProjectItem (as examples, not limited to those two) for the current selection where only a single item is selected.

Most people seem to be using IVsMonitorSelection to get an IVSHierarchy and then use the following to get the object for the selected item (in case of a single item being selected):

var monitorSelection = (IVsMonitorSelection) Package.GetGlobalService(typeof(IVsMonitorSelection));

IntPtr hierarchyPointer, selectionContainerPointer;
uint projectItemId;
IVsMultiItemSelect multiItemSelect;

monitorSelection.GetCurrentSelection(out hierarchyPointer, out projectItemId, out multiItemSelect, out selectionContainerPointer);

var hierarchy = (IVsHierarchy) Marshal.GetObjectForIUnknown(hierarchyPointer);

Marshal.Release(hierarchyPointer);
Marshal.Release(selectionContainerPointer);

object o;

hierarchy.GetProperty((uint) projectItemId, (int) __VSHPROPID.VSHPROPID_ExtObject, out o);

However, GetProperty returns E_NOTIMPL here. Am I using the wrong parameters? Is there an alternative solution perhaps?

回答1:

You can use dte.ToolWindows.SolutionExplorer.SelectedItems like this:

EnvDTE.ProjectItem projectItem = GetSelectedSolutionExplorerItem().Object as EnvDTE.ProjectItem;

    private EnvDTE.UIHierarchyItem GetSelectedSolutionExplorerItem()
    {
        EnvDTE.UIHierarchy solutionExplorer = dte.ToolWindows.SolutionExplorer;
        object[] items = solutionExplorer.SelectedItems as object[];
        if (items.Length != 1)
            return null;

        return items[0] as EnvDTE.UIHierarchyItem;
    }


回答2:

Based on the answer from Sergey, I found dte.SelectedItems, which is even "more strongly-typed" and does not require casting to an array containing UIHierarchy items.

The result is now:

dte.SelectedItems.Item(1).ProjectItem