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

Thi*_*sma 3 c# com visual-studio vsix visual-studio-2015

我有兴趣为当前选择获取一个 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);
Run Code Online (Sandbox Code Playgroud)

但是,GetProperty在此处返回 E_NOTIMPL。我是否使用了错误的参数?也许有替代解决方案?

Ser*_*sov 5

您可以像这样使用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;
    }
Run Code Online (Sandbox Code Playgroud)