问题
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