简体   繁体   中英

In a VS 2015 extension, how can I get the selected object in the Solution Explorer?

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?

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;
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM