b.holz
b.holz

Reputation: 237

VSIX Get Project associated with its Context Menu

I want to create a context menu command for a project. I managed to get the command to show on the right menu by setting the id in the .vsct file to "IDM_VS_CTXT_PROJNODE". And my code example is called correctly:

    private FirstCommand(AsyncPackage package, OleMenuCommandService commandService)
    {
        this.package = package ?? throw new ArgumentNullException(nameof(package));
        commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

        var menuCommandID = new CommandID(CommandSet, CommandId);
        var menuItem = new MenuCommand(StartNotepad, menuCommandID);
        commandService.AddCommand(menuItem);
    }


    private void StartNotepad(object sender, EventArgs e)
    {
        //example code  
        /*var process = new Process();
        process.StartInfo.FileName = "Notepad.exe";
        process.Start();*/
    }

I now need Information about the project (directory, name etc). But all examples on vsix projects only show how to get the current project (I don't even know whether that is the project I clicked on) or don't work for me. They are all old and I don't know if they are currently best practice.

So my question is how do I get information about the project in StartNotepad()? Thanks for your help.

Upvotes: 1

Views: 530

Answers (2)

b.holz
b.holz

Reputation: 237

Sergey's answer helped me to find the solution. The only think missing from it was how to get the dte in an async way:

private EnvDTE.UIHierarchyItem GetSelectedSolutionExplorerItem()
{
    ThreadHelper.ThrowIfNotOnUIThread();
    var dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE2;
    if (dte == null) return null;
    var solutionExplorer = dte.ToolWindows.SolutionExplorer;
    object[] items = solutionExplorer.SelectedItems as object[];
    if (items.Length != 1)
        return null;

    return items[0] as UIHierarchyItem;
}

Upvotes: 2

Sergey Vlasov
Sergey Vlasov

Reputation: 27900

Use the following method to get an item you clicked on:

private EnvDTE.UIHierarchyItem GetSelectedSolutionExplorerItem()
{
    EnvDTE.UIHierarchy solutionExplorer = dte.ToolWindows.SolutionExplorer;
    object[] items = solutionExplorer.SelectedItems as object[];
    if (items.Length != 1)
        return null;

    return items[0] as EnvDTE.UIHierarchyItem;
}

And then convert it to a project with GetSelectedSolutionExplorerItem()?.Object as EnvDTE.Project.

Upvotes: 2

Related Questions