IMenuCommandService.AddCommand(MenuCommand) Method

Definition

Adds the specified standard menu command to the menu.

public:
 void AddCommand(System::ComponentModel::Design::MenuCommand ^ command);
public void AddCommand (System.ComponentModel.Design.MenuCommand command);
abstract member AddCommand : System.ComponentModel.Design.MenuCommand -> unit
Public Sub AddCommand (command As MenuCommand)

Parameters

command
MenuCommand

The MenuCommand to add.

Exceptions

The CommandID of the specified MenuCommand is already present on a menu.

Remarks

The MenuCommands and StandardCommands enumerations contain CommandID identifiers for predefined standard commands and menu commands that are already associated with a location on a particular menu.

Note

An attempt to add a menu command with an already existing CommandID will throw an InvalidOperationException. When adding a menu command, be sure to check that it is not already on a menu using the FindCommand method, or use exception handling wisely.

You can attach an event handler to a predefined menu command with the following procedure:

  1. If the menu command to link with an event handler has been added to a menu, or is located with the FindCommand method, consider whether you wish to restore this menu command later, and whether you want to invoke the current event handler from your new event handler. If your code might restore the menu command or chain the invocation of event handlers, be sure to store a reference to the menu command somewhere.

  2. Ensure that any previously existing menu command with the same CommandID has been removed from the menu using the RemoveCommand method.

  3. Create a new MenuCommand and specify your event handler in the constructor, along with a CommandID representing the command to add. Each standard menu command is associated with a predefined menu location where it is added to. The supported command IDs are defined in the StandardCommands and MenuCommands enumerations.

  4. If you want to invoke any preexisting event handler for the menu command, call the Invoke method of the menu command you have replaced on the menu from the event handler that handles the invoke event of your menu command.

  5. If you are interested in restoring the event handler of a preexisting menu command that you have replaced, add the stored, preexisting menu command after you remove the replacement menu command you created. You may want to add this behavior to the Dispose method for your type.

Applies to

See also