Change the text of a menu command
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
The following steps show how to change the text label of a menu command by using the IMenuCommandService service.
Changing a menu command label with the IMenuCommandService
Create a VSIX project named
MenuText
with a menu command named ChangeMenuText. For more information, see Create an extension with a menu command.In the .vsct file, add the
TextChanges
flag to your menu command, as shown in the following example.<Button guid="guidChangeMenuTextPackageCmdSet" id="ChangeMenuTextId" priority="0x0100" type="Button"> <Parent guid="guidChangeMenuTextPackageCmdSet" id="MyMenuGroup" /> <Icon guid="guidImages" id="bmpPic1" /> <CommandFlag>TextChanges</CommandFlag> <Strings> <ButtonText>Invoke ChangeMenuText</ButtonText> </Strings> </Button>
In the ChangeMenuText.cs file, create an event handler that will be called before the menu command is displayed.
private void OnBeforeQueryStatus(object sender, EventArgs e) { var myCommand = sender as OleMenuCommand; if (null != myCommand) { myCommand.Text = "New Text"; } }
You can also update the status of the menu command in this method by changing the Visible, Checked, and Enabled properties on the OleMenuCommand object.
In the ChangeMenuText constructor, replace the original command initialization and placement code with code that creates a OleMenuCommand (rather than a
MenuCommand
) that represents the menu command, adds the BeforeQueryStatus event handler, and gives the menu command to the menu command service.Here is what it should look like:
private ChangeMenuText(AsyncPackage package, OleMenuCommandService commandService) { this.package = package ?? throw new ArgumentNullException(nameof(package)); commandService = commandService ?? throw new ArgumentNullException(nameof(commandService)); var menuCommandID = new CommandID(CommandSet, CommandId); var menuItem = new OleMenuCommand(this.Excute, menuCommandID); menuItem.BeforeQueryStatus += new EventHandler(OnBeforeQueryStatus); commandService.AddCommand(menuItem); }
Build the project and start debugging. The experimental instance of Visual Studio appears.
On the Tools menu you should see a command named Invoke ChangeMenuText.
Click the command. You should see the message box announcing that MenuItemCallback has been called. When you dismiss the message box, you should see that the name of the command on the Tools menu is now New Text.