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

◇◆丶佛笑我妖孽 提交于 2021-01-29 09:00:35

问题


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?


回答1:


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;

}



回答2:


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


来源:https://stackoverflow.com/questions/50989207/how-can-i-enable-disable-command-in-visual-studio-2017-vsix-c-sharp-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!