我正在使用 C# VSIX 项目开发 Visual Studio 2017 的扩展。我需要根据 .ini 文件中的设置创建可变数量的命令。我想创建最大数量的命令(因为在 VSIX 项目中,每个命令都需要一个新的 .cs 文件),并且只启用写在 .ini 文件中的命令。不幸的是,我不知道如何禁用命令。当布尔值变为真时,我需要启用命令。
我已经看到我需要使用 OleMenuCommand 类,但我没有 Initialize() 和 StatusQuery() 方法。如何动态启用我的命令?
我正在使用 C# VSIX 项目开发 Visual Studio 2017 的扩展。我需要根据 .ini 文件中的设置创建可变数量的命令。我想创建最大数量的命令(因为在 VSIX 项目中,每个命令都需要一个新的 .cs 文件),并且只启用写在 .ini 文件中的命令。不幸的是,我不知道如何禁用命令。当布尔值变为真时,我需要启用命令。
我已经看到我需要使用 OleMenuCommand 类,但我没有 Initialize() 和 StatusQuery() 方法。如何动态启用我的命令?
要在 Visual Studio 中启用/禁用命令,您可以订阅以下BeforeQueryStatus
事件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();
}
方法的可能实现MyCommandStatus()
可以是:
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;
}
当您创建OleMenuCommand以使用 OleMenuCommandService 添加时,您可以订阅BeforeQueryStatus事件并在其中动态启用/禁用命令:
private void OnQueryStatus(object sender)
{
Microsoft.VisualStudio.Shell.OleMenuCommand menuCommand =
sender as Microsoft.VisualStudio.Shell.OleMenuCommand;
if (menuCommand != null)
menuCommand.Visible = menuCommand.Enabled = MyCommandStatus();
}