【问题标题】:Visual Studio Extensions Get Project PathVisual Studio 扩展获取项目路径
【发布时间】:2017-07-18 13:36:26
【问题描述】:
我正在为 Visual Studio 2017 编写一个扩展,该扩展可在项目的上下文菜单中使用(通过右键单击等)
IDM_VS_CTXT_PROJNODE
我的问题是我什么时候进入
private void MenuItemCallback(object sender, EventArgs e)
如何获取项目路径?
【问题讨论】:
标签:
c#
visual-studio-2017
visual-studio-extensions
【解决方案1】:
请检查以下代码,它使用 SVsShellMonitorSelection 服务,您可以获得对所选层次结构的引用作为 IVsHierarchy,这反过来又允许我获得对所选对象的引用。然后可以根据在解决方案资源管理器中选择的内容将其转换为诸如 Project、ProjectItem 等类。
private void MenuItemCallback(object sender, EventArgs e)
{
string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
string title = "ItemContextCommand";
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;
string projectPath = selectedProject.FullName;
// Show a message box to prove we were here
VsShellUtilities.ShowMessageBox(
this.ServiceProvider,
message,
projectPath,
OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}