2017-07-18 54 views
0

我寫的Visual Studio 2017年的延伸,擴展是在項目的上下文菜單(右鍵單擊等)使用的Visual Studio擴展獲取項目路徑

IDM_VS_CTXT_PROJNODE 

我的問題是,當我輸入

private void MenuItemCallback(object sender, EventArgs e)  

如何獲取項目路徑?

回答

1

請檢查以下代碼,它使用SVsShellMonitorSelection服務,您可以獲取對所選層次結構的引用作爲IVsHierarchy,這反過來又允許我獲取對所選對象的引用。然後,可以根據Solution Explorer中選擇的內容將其轉換爲諸如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); 
     } 
+0

這很好地完成了這項工作。謝謝。 – SuperAaz

相關問題