从Solution Explorer中选择的项目

hav*_*dhu 5 .net c# visual-studio-2010 vs-extensibility vsix

我正在为Visual Studio 2010(vsix)编写自定义包.

我需要做的是在解决方案资源管理器中向项目节点添加上下文菜单按钮.

右键单击Project节点时,我已设法显示上下文菜单,但我的下一个挑战是获取对已单击的Project对象的引用.目前,我可以使用下面的代码浏览IDE中的活动文档来获取项目.

DTE dte = (DTE)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
Project project = dte.ActiveDocument.ProjectItem.ContainingProject;
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何获得对解决方案资源管理器中所选项目的类似引用?

hav*_*dhu 11

我想到了.不妨分享信息.

通过使用该SVsShellMonitorSelection服务,我可以将所选层次结构的引用作为a IVsHierarchy,这反过来允许我获得对所选对象的引用.这然后可以转换为类,如Project,ProjectItem等的基础上,什么是在解决方案资源管理器中选择.便利!

IntPtr hierarchyPointer, selectionContainerPointer;
Object selectedObject  = null;
IVsMultiItemSelect multiItemSelect;
uint projectItemId;

IVsMonitorSelection monitorSelection = 
        (IVsMonitorSelection)Package.GetGlobalService(
        typeof(SVsShellMonitorSelection));

monitorSelection.GetCurrentSelection(out hierarchyPointer, 
                                     out projectItemId, 
                                     out multiItemSelect, 
                                     out selectionContainerPointer);

IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown(
                                     hierarchyPointer, 
                                     typeof(IVsHierarchy)) as IVsHierarchy;

if (selectedHierarchy != null)
{
    ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty(
                                      projectItemId,
                                      (int)__VSHPROPID.VSHPROPID_ExtObject, 
                                      out selectedObject));
}

Project selectedProject = selectedObject as Project;
Run Code Online (Sandbox Code Playgroud)

这是源头