代码之家  ›  专栏  ›  技术社区  ›  Aazarus

Visual Studio扩展获取项目路径

  •  3
  • Aazarus  · 技术社区  · 8 年前

    我正在为Visual Studio 2017编写一个扩展,该扩展可以在项目的上下文菜单中使用(通过右键单击等)

    IDM_VS_CTXT_PROJNODE
    

    private void MenuItemCallback(object sender, EventArgs e)       
    

    如何获得项目路径?

    1 回复  |  直到 8 年前
        1
  •  7
  •   Zhanglong Wu - MSFT    8 年前

    请检查以下代码,这些代码使用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);
            }
    
    推荐文章