cristian leonardi
cristian leonardi

Reputation: 3

How can I enable/disable command in Visual Studio 2017 VSIX C# project

I'm developing an extension for Visual Studio 2017 using a C# VSIX project. I need to create a variable number of commands based on settings in a .ini file. I thought to create a maximum number of commands (because in a VSIX project every command needs a new .cs file), and enable only the commands written in the .ini file. Unfortunately I don't know how to disable a command. I need to enable the commands when a boolean becomes true.

I've seen that I need to use the OleMenuCommand class, but I do not have Initialize() and StatusQuery() methods. How can I dynamically enable my commands?

Upvotes: 0

Views: 2315

Answers (2)

Ionut Enache
Ionut Enache

Reputation: 521

To enable/disable commands in Visual Studio you can subscribe to the BeforeQueryStatus event of your OleMenuCommand:

myOleMenuCommand.BeforeQueryStatus += QueryCommandHandler;

private void QueryCommandHandler(object sender)
{
        var menuCommand = sender as Microsoft.VisualStudio.Shell.OleMenuCommand;
        if (menuCommand != null)
            menuCommand.Visible = menuCommand.Enabled = MyCommandStatus();
}

A possible implementation of MyCommandStatus() method can be:

public bool MyCommandStatus()
{
    // do this if you want to disable your commands when the solution is not loaded
    if (false == mDte.Solution.IsOpen)
      return false;

    // do this if you want to disable your commands when the Visual Studio build is running
    else if (true == VsBuildRunning)
      return false;

    // Write any condition here

    return true;

}

Upvotes: 4

Sergey Vlasov
Sergey Vlasov

Reputation: 27900

When you create an OleMenuCommand to add with OleMenuCommandService, you can subscribe to the BeforeQueryStatus event and inside it dynamically enable/disable the command:

    private void OnQueryStatus(object sender)
    {
            Microsoft.VisualStudio.Shell.OleMenuCommand menuCommand =
                sender as Microsoft.VisualStudio.Shell.OleMenuCommand;
            if (menuCommand != null)
                menuCommand.Visible = menuCommand.Enabled = MyCommandStatus();
    }

Upvotes: 0

Related Questions