Search code examples
c#visual-studiocommandvsixvsct

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?


Solution

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