Share via


Procedura: aggiungere e gestire comandi

Mediante i seguenti oggetti è possibile creare, gestire e modificare i comandi dei menu e delle barre degli strumenti di Visual Studio.

Nome oggetto

Description

IDTCommandTarget

Fornisce metodi per la determinazione dello stato o l'esecuzione di un comando aggiunto all'ambiente di sviluppo integrato (IDE) mediante il metodo AddNamedCommand2.

Commands2

Rappresenta tutti i comandi nell'ambiente di sviluppo integrato (IDE).

Command

Rappresenta un comando nell'ambiente di sviluppo integrato (IDE).

CommandEvents

Fornisce eventi di comando per i componenti aggiuntivi.

CommandBarEvents

Fornisce un evento Click quando si fa clic su un controllo o un comando di una barra dei comandi.

Nota

Se il comando non viene più visualizzato sulla relativa barra dei comandi, se si aggiunge un nuovo comando o se ne modifica uno esistente, o se si desidera ricreare il comando, chiudere tutte le istanze di Visual Studio e fare doppio clic sul file ReCreateCommands.reg nella cartella contenente il codice sorgente per il componente aggiuntivo.

Utilizzando questi oggetti è possibile:

  • Aggiungere o rimuovere una barra dei comandi nell'ambiente di sviluppo integrato di Visual Studio (AddCommandBar e RemoveCommandBar).

  • Aggiungere un nuovo comando con nome a una barra degli strumenti o a un menu (tramite il metodo AddNamedCommand2).

  • Richiamare un comando o un comando con nome (tramite i metodi Raise e Exec).

  • Ottenere lo stato di un comando (tramite i metodi CommandInfo e QueryStatus).

    Nota

    Non è possibile connettere un evento CommandBarEvents per i controlli CommandBar creati per un nuovo comando tramite AddNamedCommand2.

Nota

È possibile che le finestre di dialogo e i comandi di menu visualizzati siano diversi da quelli descritti nella Guida a seconda delle impostazioni attive o dell'edizione del programma. Queste procedure sono state sviluppate con le Impostazioni generali per lo sviluppo attive. Per modificare le impostazioni, scegliere Importa/Esporta impostazioni dal menu Strumenti. Per ulteriori informazioni, vedere Gestione delle impostazioni.

Esempio

Nell'esempio seguente viene utilizzato:

Nella procedura riportata di seguito viene illustrato come è possibile visualizzare un componente aggiuntivo come comando nel menu Strumenti di Visual Studio. Aggiungere la prima sezione di codice al metodo OnConnection del componente aggiuntivo creato. Nei metodi Exec e QueryStatus verificare che la riga If cmdName = "MyAddin1.Connect.MyAddin1" Then corrisponda al nome del componente aggiuntivo.

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;
        }
    }
}

Vedere anche

Attività

Procedura: creare un componente aggiuntivo

Procedura dettagliata: creazione di una procedura guidata

Concetti

Controllo di progetti e soluzioni

Grafico del modello a oggetti di automazione

Altre risorse

Creazione e controllo delle finestre di ambiente

Creazione di componenti aggiuntivi e di procedure guidate

Riferimenti su Extensibility e automazione