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

2

3

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?

Sleight answered 20/4, 2016 at 20:12 Comment(0)
S
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

Sleight answered 23/4, 2016 at 16:55 Comment(0)
L
5

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;
    }
Ludovico answered 21/4, 2016 at 6:59 Comment(1)
This is so much simpler and it works like a charm! Thank you, this has resolved my issue.Sleight
S
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

Sleight answered 23/4, 2016 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.