Comment : ajouter et gérer des commandes

Les compléments Visual Studio sont déconseillés dans Visual Studio 2013. Vous devriez mettre vos compléments à niveau vers des extensions VSPackage. Pour plus d'informations sur les mises à jour, consultez FAQ : conversion de compléments en extensions VSPackage.

Les objets suivants vous permettent de créer, de gérer et de manipuler des commandes dans les menus et barres d'outils de Visual Studio.

Nom de l'objet

Description

IDTCommandTarget

Fournit des méthodes permettant de déterminer l'état d'une commande ajoutée à l'environnement de développement intégré (IDE) à l'aide de la méthode AddNamedCommand2, ou d'exécuter cette commande.

Commands2

Représente toutes les commandes de l'IDE.

Command

Représente une commande de l'IDE.

CommandEvents

Fournit des événements de commandes pour des compléments.

CommandBarEvents

Fournit un événement Click lorsqu'un clic est effectué sur un contrôle d'une barre de commandes.

Notes

Si votre commande n'apparaît plus sur la barre de commandes appropriée, ou si vous ajoutez une nouvelle commande ou modifiez une commande existante, ou si vous souhaitez recréer la commande, fermez toutes les instances de Visual Studio et double-cliquez sur le fichier nommé ReCreateCommands.reg dans le dossier qui contient le code source de votre complément.

À l'aide de ces objets, vous pouvez :

  • Ajoutez ou supprimez une barre de commandes dans l'IDE de Visual Studio (méthodes AddCommandBar et RemoveCommandBar).

  • ajouter une nouvelle commande nommée à une barre d'outils ou à un menu (méthode AddNamedCommand2) ;

  • appeler une commande ou une commande nommée (méthodes Raise et Exec) ;

  • obtenir l'état d'une commande (méthodes CommandInfo et QueryStatus).

    Notes

    Vous ne pouvez pas connecter un événement CommandBarEvents pour des contrôles CommandBar qui ont été créés pour une nouvelle commande ajoutée via AddNamedCommand2.

Notes

Les boîtes de dialogue et les commandes de menu qui s'affichent peuvent être différentes de celles qui sont décrites dans l'aide, en fonction de vos paramètres actifs ou de l'édition utilisée.Ces procédures ont été développées avec les paramètres de développement généraux actifs.Pour modifier vos paramètres, sélectionnez Importation et exportationde paramètres dans le menu Outils.Pour plus d'informations, consultez Paramètres Visual Studio.

Exemple

L'exemple suivant utilise les éléments :

La procédure montre comment faire apparaître un complément en tant que commande dans le menu Outils de Visual Studio. Ajoutez la première section de code à la méthode OnConnection du complément que vous créez. Dans les méthodes Exec et QueryStatus, vérifiez que la ligne, If cmdName = "MyAddin1.Connect.MyAddin1" Then, reflète le nom de votre complément.

Public Sub OnConnection(ByVal application As Object, _
  ByVal connectMode As ext_ConnectMode, ByVal addInInst _
  As Object, ByRef custom As Array) Implements _
  IDTExtensibility2.OnConnection
    _applicationObject = CType(application, DTE2)
    _addInInstance = CType(addInInst, AddIn)
    If connectMode = ext_ConnectMode.ext_cm_UISetup Then
        Dim commands As Commands2 = CType(_applicationObject. _
          Commands, Commands2)
        Dim toolsMenuName As String
        Try
            Dim resourceManager As System.Resources. _
              ResourceManager = New System.Resources. _
              ResourceManager("MyAddin1.CommandBar", _
              System.Reflection.Assembly.GetExecutingAssembly())

              Dim cultureInfo As System.Globalization. _
                CultureInfo = New System.Globalization. _
                CultureInfo(_applicationObject.LocaleID)
              toolsMenuName = resourceManager.GetString _
                (String.Concat(cultureInfo. _
                TwoLetterISOLanguageName, "Tools"))
        Catch e As Exception
            toolsMenuName = "Tools"
        End Try

        Dim commandBars As CommandBars = CType(_applicationObject _
          .CommandBars, CommandBars)
        Dim menuBarCommandBar As CommandBar = commandBars. _
          Item("MenuBar")
        Dim toolsControl As CommandBarControl = _
          menuBarCommandBar.Controls.Item(toolsMenuName)
        Dim toolsPopup As CommandBarPopup = CType(toolsControl, _
          CommandBarPopup)

        Try
            Dim command As Command = commands.AddNamedCommand2 _
              (_addInInstance, "MyAddin1", "MyAddin1", _
              "Executes the command for MyAddin1", True, 59, _
              Nothing, CType(vsCommandStatus. _
              vsCommandStatusSupported, Integer) + CType _
              (vsCommandStatus.vsCommandStatusEnabled, Integer), _
              vsCommandStyle.vsCommandStylePictAndText, _
              vsCommandControlType.vsCommandControlTypeButton)
            command.AddControl(toolsPopup.CommandBar, 1)
        Catch argumentException As System.ArgumentException
            MsgBox(argumentException.ToString)
        End Try
    End If
End Sub

'Code for the QueryStatus method.
Public Sub QueryStatus(ByVal commandName As String, _
  ByVal neededText As vsCommandStatusTextWanted, _
  ByRef status As vsCommandStatus, ByRef commandText _
  As Object) Implements IDTCommandTarget.QueryStatus
    If neededText = vsCommandStatusTextWanted. _
      vsCommandStatusTextWantedNone Then
        If commandName = "MyAddin1.Connect.MyAddin1" Then
            status = CType(vsCommandStatus. _
              vsCommandStatusEnabled + vsCommandStatus. _
              vsCommandStatusSupported, vsCommandStatus)
        Else
            status = vsCommandStatus.vsCommandStatusUnsupported
        End If
    End If
End Sub

' Code for the Exec method.
Public Sub Exec(ByVal commandName As String, ByVal executeOption _
  As vsCommandExecOption, ByRef varIn As Object, ByRef varOut _
  As Object, ByRef handled As Boolean) Implements IDTCommandTarget.Exec
    handled = False
    If executeOption = vsCommandExecOption. _
      vsCommandExecOptionDoDefault Then
        If commandName = "MyAddin1.Connect.MyAddin1" Then
            handled = True
            Exit Sub
        End If
    End If
End Sub
public class Connect : Object, IDTExtensibility2, IDTCommandTarget
{
    public Connect()
    {
    }

public void OnConnection(object application, ext_ConnectMode 
  connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    if(connectMode == ext_ConnectMode.ext_cm_UISetup)
    {
        object []contextGUIDS = new object[] { };
        Commands2 commands = (Commands2)_applicationObject.Commands;
        string toolsMenuName;
        try
        {
            ResourceManager resourceManager = new
            ResourceManager("MyAddin4.CommandBar", 
            Assembly.GetExecutingAssembly());
            CultureInfo cultureInfo = new 
              System.Globalization.CultureInfo
             (_applicationObject.LocaleID);
            string resourceName =  
            String.Concat(cultureInfo.TwoLetterISOLanguageName, 
              "Tools");
            toolsMenuName = resourceManager.GetString(resourceName);
        }
        catch
        {
            toolsMenuName = "Tools";
        }

        CommandBar menuBarCommandBar = 
            ((CommandBars)_applicationObject.CommandBars)["MenuBar"];
        CommandBarControl toolsControl = 
          menuBarCommandBar.Controls[toolsMenuName];
        CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;
        try
        {
            Command command = commands.AddNamedCommand2(_addInInstance, 
              "MyAddin4", "MyAddin4", "Executes the command for 
              MyAddin4", true, 59, ref contextGUIDS, 
              (int)vsCommandStatus.vsCommandStatusSupported+
              (int)vsCommandStatus.vsCommandStatusEnabled, 
              (int)vsCommandStyle.vsCommandStylePictAndText,  
              vsCommandControlType.vsCommandControlTypeButton);

            if((command != null) && (toolsPopup != null))
            {
                command.AddControl(toolsPopup.CommandBar, 1);
            }
        }
        catch(System.ArgumentException)
        {
        }
    }
}

public void QueryStatus(string commandName, vsCommandStatusTextWanted 
  neededText, ref vsCommandStatus status, ref object commandText)
{
    if(neededText == 
      vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
    {
        if(commandName == "MyAddin4.Connect.MyAddin4")
        {
            status = (vsCommandStatus)vsCommandStatus.
              vsCommandStatusSupported|vsCommandStatus.
              vsCommandStatusEnabled;
            return;
        }
    }
}

public void Exec(string commandName, vsCommandExecOption executeOption, 
  ref object varIn, ref object varOut, ref bool handled)
{
    handled = false;
    if(executeOption == 
      vsCommandExecOption.vsCommandExecOptionDoDefault)
    {
        if(commandName == "MyAddin4.Connect.MyAddin4")
        {
            handled = true;
            return;
        }
    }
}

Voir aussi

Tâches

Comment : créer un complément

Procédure pas à pas : création d'un Assistant

Concepts

Contrôle de projets et de solutions

Graphique Modèle d'objet Automation

Autres ressources

Création et contrôle de fenêtres d'environnement

Création de compléments et d'Assistants

Guide de référence de l'extensibilité et de l'automation