Search code examples
c#visual-studio-2017visual-studio-extensions

Visual Studio Extensions Get Project Path


I'm writing an extension for Visual Studio 2017, the extension is available in the context menu of a project (by right-clicking etc) using

IDM_VS_CTXT_PROJNODE

My question is when I enter

private void MenuItemCallback(object sender, EventArgs e)       

how do I get the project path?


Solution

  • Please check the following code, which use the SVsShellMonitorSelection service you can get a reference to the selected hierarchy as a IVsHierarchy, which in turn allows me to get a reference to the selected object. This may then be cast to classes such as Project, ProjectItem, etc, based on what is selected in the Solution Explorer.

    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);
            }