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

你离开我真会死。 提交于 2019-12-10 20:16:57

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/36754218/in-a-vs-2015-extension-how-can-i-get-the-selected-object-in-the-solution-explor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!