在 VS 2015 扩展中,如何在解决方案资源管理器中获取选定的对象?

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

我有兴趣为当前选择获取一个 Project 或 ProjectItem(例如,不限于这两个),其中仅选择了一个项目。

大多数人似乎都在使用 IVsMonitorSelection 获取 IVSHierarchy 然后使用以下内容获取所选项目的对象(在选择单个项目的情况下):

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

不过,GetPropertyreturnsE_NOTIMPL这里。我使用了错误的参数吗?也许有替代解决方案?

您可以像这样使用dte.ToolWindows.SolutionExplorer.SelectedItems

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

根据 Sergey 的回答,我发现 dte.SelectedItems,它甚至是 "more strongly-typed",并且不需要转换为包含 UIHierarchy 的数组 项目。

现在的结果是:

dte.SelectedItems.Item(1).ProjectItem