【问题标题】:In a VS 2015 extension, how can I get the selected object in the Solution Explorer?在 VS 2015 扩展中,如何在解决方案资源管理器中获取选定对象?
【发布时间】:2016-08-13 17:55:20
【问题描述】:

我有兴趣为当前选择获取一个 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。我使用了错误的参数吗?是否有替代解决方案?

【问题讨论】:

    标签: c# visual-studio com visual-studio-2015 vsix


    【解决方案1】:

    您可以像这样使用 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;
        }
    

    【讨论】:

    • 这要简单得多,而且效果很好!谢谢,这解决了我的问题。
    【解决方案2】:

    根据 Sergey 的回答,我找到了 dte.SelectedItems,它甚至是“更强大的类型”,并且不需要强制转换为包含 UIHierarchy 的数组 项目。

    现在的结果是:

    dte.SelectedItems.Item(1).ProjectItem

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 2015-11-07
      • 1970-01-01
      相关资源
      最近更新 更多