How to: Change the Text of a Menu Command

The following procedure shows how to change the text of a menu command by using managed code and the IMenuCommandService service.

Procedure

To change a menu command label by using IMenuCommandService

  1. In the .vstc file, add the TextChanges flag to your menu command, as shown in the following example.

    <Button guid="guidMenuTextCmdSet" id="cmdidMyTextCommand" 
            priority="0x0100" type="Button">
      <Parent guid="guidMenuTextCmdSet" id="MyMenuGroup" />
      <Icon guid="guidImages" id="bmpPic1" />
      <CommandFlag>TextChanges</CommandFlag>
      <Strings>
        <CommandName>cmdidMyTextCommand</CommandName>
        <ButtonText>My Text</ButtonText>
      </Strings>
    </Button>
    
  2. In the VSPackage, create an event handler to 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.

  3. Add code that performs the following actions when the VSPackage is initialized.

    1. Query for the menu command service.

    2. Create a OleMenuCommand object that represents the menu command.

    3. Add the BeforeQueryStatus event handler.

    4. Give the menu command to the menu command service.

    protected override void Initialize()
    {
        var mcs = GetService(typeof(IMenuCommandService)) 
            as OleMenuCommandService;
        if ( null != mcs )
        {
            var menuCommandID = new CommandID(
                GuidList.guidMenuTextCmdSet, 
                (int)PkgCmdIDList.cmdidMyTextCommand);
            var menuItem = new OleMenuCommand(
                MenuItemCallback, menuCommandID );
            menuItem.BeforeQueryStatus += 
                new EventHandler(OnBeforeQueryStatus);
            mcs.AddCommand( menuItem );
        }
    }
    

    When you use the package wizard to create a menu command, it adds the required code automatically. However, it declares the menu command as a MenuCommand object and it does not add the BeforeQueryStatus handler. Therefore, you must change the menu command declaration to use OleMenuCommand and add the handler on the next line.

    The package file must include the System.ComponentModel.Design and Microsoft.VisualStudio.Shell namespaces to access the IMenuCommandService interface and the OleMenuCommand object.

See Also

Other Resources

Common Menu Tasks