Condividi tramite


How to: Change the Appearance of a Command

You can provide feedback to your user by changing the appearance of a command. For example, you may want a command to look different when it is unavailable. You can make commands available or unavailable, hide or show them, or check or uncheck them on the menu.

To change the appearance of a command, perform one of these actions:

  • Specify the appropriate flags in the command definition in the command table file.

  • Use the OleMenuCommandService service.

  • Implement the IOleCommandTarget interface and modify the raw command objects.

The following steps show how to find and update the appearance of a command by using the Managed Package Framework (MPF).

To change the appearance of a menu command

  1. Follow the instructions in How to: Change the Text of a Menu Command to create a menu item named New Text.

  2. In the VSPackage source file named, for example, MenuTextPackage.cs, add the following lines to the end of the MenuItemCallback method.

    var command = sender as OleMenuCommand;
    if (command.Text == "New Text") EnableMyCommand(command.CommandID.ID, false);
    
  3. Obtain the command that you want to update from the OleMenuCommandService object and then set the appropriate properties on the command object. For example, the following method makes the specified command from a VSPackage command set available or unavailable.

    <PrincipalPermission(SecurityAction.Demand)> _
    Public Function EnableMyCommand(ByVal cmdID As Integer, ByVal fEnableCmd As Boolean) As Boolean
        Dim fCmdUpdated As Boolean = False
        Dim mcs As OleMenuCommandService = TryCast(Me.GetService(GetType(IMenuCommandService)), OleMenuCommandService)
        Dim newCmdID As CommandID = New CommandID(GuidList.guidMenuTextCmdSet, cmdID)
        Dim mc As MenuCommand = mcs.FindCommand(newCmdID)
        If mc IsNot Nothing Then
            mc.Enabled = fEnableCmd
            fCmdUpdated = True
        End If
        Return fCmdUpdated
    End Function
    
    [PrincipalPermission(SecurityAction.Demand)]
    public bool EnableMyCommand(int cmdID, bool fEnableCmd)
    {
        bool fCmdUpdated = false;
        var mcs = this.GetService(typeof(IMenuCommandService))
                as OleMenuCommandService;
        var newCmdID = new CommandID(GuidList.guidMenuTextCmdSet, cmdID);
        MenuCommand mc = mcs.FindCommand(newCmdID);
        if (mc != null)
        {
            mc.Enabled = fEnableCmd;
            fCmdUpdated = true;
        }
        return fCmdUpdated;
    }
    

    This makes the menu item named New Text unavailable after it has been clicked.

See Also

Concepts

How VSPackages Add User Interface Elements to the IDE

Other Resources

Commands, Menus, and Toolbars

Common Tasks with Commands, Menus, and Toolbars

Visual Studio Command Table (.Vsct) Files