The following procedure shows how to support changing the text of a menu command from managed code using the IMenuCommandService service.
注意
Beginning with Visual Studio 2008 SDK, use XML Command Table (.vsct) files instead of command table configuration (.ctc) files to define how menus and commands appear in your VSPackages. For more information, see XML-Based Command Table Configuration (.vsct) Files.
Procedure
Change the Menu Label using IMenuCommandService
In your .ctc file, add the TextChanges flag to your menu command. For example:
BUTTONS_BEGIN guidMyCmdSet:cmdidMyCommand, // command guidMyCmdSet:MyMenuGroup // parent 0x0100, // priority guidOfficeIcon:msotcidNoIcon, // icon (no icon in this case) BUTTON, // type TextOnly | TextChanges, // Text only and it changes "My Text"; BUTTONS_ENDNote that the command could also have been marked as IconAndText instead of TextOnly.
In your VSPackage, create a new event handler that is called before the menu command is displayed. For example:
class MyPackage : Package { public void OnBeforeQueryStatus(object sender, EventArgs e) { Microsoft.VisualStudio.Shell.OleMenuCommand myCommand; myCommand = sender as Microsoft.VisualStudio.Shell.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.
When the VSPackage initializes, do the following:
Query for the menu command service
Create a new OleMenuCommand object representing your menu command
Add the BeforeQueryStatus event handler, and
Give the menu command to the menu command service.
using System.ComponentModel.Design; // for IMenuCommandService, CommandID using Microsoft.VisualStudio.Shell; // For OleMenuCommandService, OleCommand class MyPackage : Package { protected override void Initialize() { OleMenuCommandService menuService; menuService = this.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != menuService) { CommandID commandId = new CommandID(guidMyCmdSet,cmdidMyCommand); OleMenuCommand myCommand = new OleMenuCommand(new EventHandler(OnMyCommandHandler), commandId); myCommand.BeforeQueryStatus += new EventHandler(OnBeforeQueryStatus); menuService.AddCommand(myCommand); } } }