C# 从解决方案资源管理器中选择的项目
我正在为VisualStudio2010(vsix)编写一个定制包 我需要做的是在解决方案资源管理器中向项目节点添加上下文菜单按钮 我已经设法在右键单击项目节点时显示上下文菜单,但我的下一个挑战是获取对已单击项目对象的引用。目前,我可以通过使用下面的代码浏览IDE中的活动文档来获取项目C# 从解决方案资源管理器中选择的项目,c#,.net,visual-studio-2010,vsix,vs-extensibility,C#,.net,Visual Studio 2010,Vsix,Vs Extensibility,我正在为VisualStudio2010(vsix)编写一个定制包 我需要做的是在解决方案资源管理器中向项目节点添加上下文菜单按钮 我已经设法在右键单击项目节点时显示上下文菜单,但我的下一个挑战是获取对已单击项目对象的引用。目前,我可以通过使用下面的代码浏览IDE中的活动文档来获取项目 DTE dte = (DTE)ServiceProvider.GlobalProvider.GetService(typeof(DTE)); Project project = dte.ActiveDocumen
DTE dte = (DTE)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
Project project = dte.ActiveDocument.ProjectItem.ContainingProject;
因此,我的问题是:如何获得解决方案资源管理器中所选项目的类似引用?我找到了答案。不妨分享一下信息 通过使用
SVsShellMonitorSelection
服务,我可以以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;
我很高兴我找到了这个,在其他任何地方都找不到如何做到这一点:我认为您缺少了
Marshal.Release(hierarchyPtr);封送放行(selectionContainerPointer)代码>以避免内存泄漏。否则太棒了!这可能是显而易见的,但作为IntPtr的新手,值得指出的是,您可以在调用Marshal.Release之前检查selectionContainerPointer==IntPtr.Zero,以避免出现空指针异常。