繁体   English   中英

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

但是, GetProperty在此返回E_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,它甚至是“更强类型”的,并且不需要转换为包含UIHierarchy项的数组。

结果现在是:

dte.SelectedItems.Item(1).ProjectItem

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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