递归查询解决方案的所有UIHierarchyItems,并找到与您的ProjectItem等效的确切UIHierarchyItem。然后调用UIHierarchyItem.Select()
UIHierarchyItem uiItem = SolutionHelper.FindHierarchyItem(dteInstance.Solution.Projects(2).ProjectItems(3));
uiItem?.Select(vsUISelectionType.vsUISelectionTypeSelect);
private static readonly EnvDTE80.DTE2 _applicationObject =
(EnvDTE80.DTE2)ServiceProvider.GlobalProvider.GetService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
public static UIHierarchy SolutionExplorerNode
{
get
{
return _applicationObject.ToolWindows.SolutionExplorer;
}
}
public static UIHierarchyItem FindHierarchyItem(object item)
{
ThreadHelper.ThrowIfNotOnUIThread();
UIHierarchyItems items = SolutionExplorerNode.UIHierarchyItems.Item(1).UIHierarchyItems;
Stack s = new Stack();
CreateItemsStack(s, item);
UIHierarchyItem last = null;
while (s.Count != 0)
{
object o = s.Pop();
last = null;
foreach (UIHierarchyItem child in items)
{
if (child.Object == o)
{
last = child;
items = child.UIHierarchyItems;
break;
}
}
}
return last;
}
private static void CreateItemsStack(Stack s, object item)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (item is ProjectItem)
{
ProjectItem pi = (ProjectItem)item;
s.Push(pi);
CreateItemsStack(s, pi.Collection.Parent);
}
else if (item is Project)
{
Project p = (Project)item;
s.Push(p);
if (p.ParentProjectItem != null)
{
CreateItemsStack(s, p.ParentProjectItem);
}
}
}