Partager via


Comment : gérer des événements Automation (Visual C#)

La procédure suivante montre comment gérer des événements liés aux fenêtres à l'aide d'un complément Visual C#.

[!REMARQUE]

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, choisissez Importation et exportation de paramètres dans le menu Outils.Pour plus d'informations, consultez Paramètres Visual Studio.

Pour gérer des événements liés aux fenêtres à l'aide de Visual C#

  1. Créez un projet de complément Visual Studio en utilisant Visual C#.

  2. Dans la méthode OnConnection, initialisez une variable pour intercepter des événements.Dans l'exemple ci-dessous, cette variable se nomme events.

    EnvDTE.Events events = _applicationObject.Events;
    
  3. Dans la méthode OnConnection, récupérez les objets événement issus du modèle Automation.

    winEvents = (EnvDTE.WindowEvents)events.get_WindowEvents(null);
    

    Dans cet exemple, la variable se nomme winEvents.D'autres objets présents dans le modèle Automation sont liés à d'autres types d'événements.Par exemple, FindEvents s'applique aux événements liés aux opérations de recherche, et TaskListEvents aux événements en rapport avec la Liste des tâches.Pour obtenir une liste exhaustive des événements disponibles, consultez Réponse aux événements d'automation.

  4. Dans la méthode OnConnection, connectez chaque délégué exposé à partir des objets événement récupérés à l'étape 3 en utilisant l'opérateur + =.Par exemple, pour connecter les délégués exposés par l'événement WindowClosing, vous utiliseriez :

    winEvents.WindowClosing += new  
    _dispWindowEvents_WindowClosingEventHandler(this.WindowClosing);
    
  5. Ajoutez des procédures pour chaque événement en rapport avec l'objet événement.Par exemple, pour gérer l'événement qui se produit lorsqu'une fenêtre est fermée (WindowClosing), vous utiliserez :

    public void WindowClosing(EnvDTE.Window closingWindow)
    {
        outputWindowPane.OutputString ("WindowEvents::WindowClosing\n");
        outputWindowPane.OutputString("\tWindow: " + 
        closingWindow.Caption + "\n");
    }
    

    Dans le cas de l'objet WindowEvents, vous devez disposer de procédures pour tous ses événements, à savoir :

  6. Enfin, pour empêcher Visual Studio de ralentir votre système en continuant à surveiller les événements liés aux fenêtres une fois le complément fermé, désactivez la gestion des événements.Dans Visual C#, pour ce faire, utilisez l'opérateur - =.Par exemple, pour désactiver la gestion des événements pour WindowClosing, vous utiliserez :

    public void OnDisconnection(ext_DisconnectMode disconnectMode, 
    ref Array custom)
    {
        if (winEvents != null)
        {
            winEvents.WindowClosing -= new 
            _dispWindowEvents_WindowClosingEventHandler     
            (this.WindowClosing);
        }
    }
    

    La gestion des événements est alors désactivée si le complément est arrêté, ou si l'IDE est arrêté tandis que le complément est encore en cours d'exécution.Une fois l'IDE arrêté, tous les compléments en cours d'exécution sont fermés automatiquement en premier.

Exemple

L'exemple suivant est un complément Visual C# de base qui montre comment intercepter et gérer des événements liés aux fenêtres dans Visual Studio.À chaque fois que des événements liés aux fenêtres se produisent, un message de notification est envoyé à la fenêtre Sortie.

namespace CSEventsAddin
{
    using System;
    using Microsoft.VisualStudio.CommandBars;
    using Extensibility;
    using EnvDTE;
    using EnvDTE80;

    public class Connect : Object, IDTExtensibility2
    {
        public Connect()
        {
        }

        public void OnConnection(object application, ext_ConnectMode 
        connectMode, object addInInst, ref Array custom)
        {
            _applicationObject = (DTE2)application;
            _addInInstance = (AddIn)addInInst;

            // Retrieve the event objects from the automation model.
            EnvDTE.Events events = _applicationObject.Events;
            // Send event messages to the Output window.
            OutputWindow outputWindow = 
            (OutputWindow)_applicationObject.Windows.Item
            (Constants.vsWindowKindOutput).Object;
            outputWindowPane = outputWindow.OutputWindowPanes.Add("DTE 
Event Information");
            // Retrieve the event objects from the automation model.
            winEvents = 
            (EnvDTE.WindowEvents)events.get_WindowEvents(null);

            // Connect to each delegate exposed from each object 
            // retrieved above.
            winEvents.WindowActivated += new 
            _dispWindowEvents_WindowActivatedEventHandler
            (this.WindowActivated);
            winEvents.WindowClosing += new  
            _dispWindowEvents_WindowClosingEventHandler
            (this.WindowClosing);
            winEvents.WindowCreated += new  
            _dispWindowEvents_WindowCreatedEventHandler
            (this.WindowCreated);
            winEvents.WindowMoved += new 
            _dispWindowEvents_WindowMovedEventHandler
            (this.WindowMoved);
        }

        public void OnDisconnection(ext_DisconnectMode disconnectMode, 
        ref Array custom)
        {
            // If the delegate handlers have been connected, then 
            // disconnect them here. 
            // If this is not done, the handlers may still 
            // fire until the next garbage collection event.
            if (winEvents != null)
            {
                winEvents.WindowActivated -= new 
                _dispWindowEvents_WindowActivatedEventHandler
                (this.WindowActivated);
                winEvents.WindowClosing -= new 
                _dispWindowEvents_WindowClosingEventHandler
                (this.WindowClosing);
                winEvents.WindowCreated -= new 
                _dispWindowEvents_WindowCreatedEventHandler
                (this.WindowCreated);
                winEvents.WindowMoved -= new 
                _dispWindowEvents_WindowMovedEventHandler
                (this.WindowMoved);
            }
        }

        // Window-related events.
        public void WindowClosing(EnvDTE.Window closingWindow)
        {
            outputWindowPane.OutputString
("WindowEvents::WindowClosing\n");
            outputWindowPane.OutputString("\tWindow: " + 
closingWindow.Caption + "\n");
        }

        public void WindowActivated(EnvDTE.Window gotFocus,   
        EnvDTE.Window lostFocus)
        {
            outputWindowPane.OutputString
("WindowEvents::WindowActivated\n");
            outputWindowPane.OutputString("\tWindow receiving focus: " 
+ gotFocus.Caption + "\n");
            outputWindowPane.OutputString("\tWindow that lost focus: " 
+ lostFocus.Caption + "\n");
        }

        public void WindowCreated(EnvDTE.Window window)
        {
            outputWindowPane.OutputString
            ("WindowEvents::WindowCreated\n");
            outputWindowPane.OutputString("\tWindow: " + window.Caption 
+ "\n");
        }

        public void WindowMoved(EnvDTE.Window window, int top, int 
        left, int width, int height)
        {
            outputWindowPane.OutputString
            ("WindowEvents::WindowMoved\n");
            outputWindowPane.OutputString("\tWindow: " + window.Caption 
+ "\n");
            outputWindowPane.OutputString("\tLocation: (" + 
top.ToString() + " , " + left.ToString() + " , " + 
width.ToString() + " , " + height.ToString() + ")\n");
        }

        public void OnAddInsUpdate(ref Array custom)
        {
        }

        public void OnStartupComplete(ref Array custom)
        {
        }

        public void OnBeginShutdown(ref Array custom)
        {
        }

        private DTE2 _applicationObject;
        private AddIn _addInInstance;
        private EnvDTE.WindowEvents winEvents;
        private OutputWindowPane outputWindowPane;
    }
}

Compilation du code

Pour compiler ce code, créez un projet de complément Visual C# et remplacez le code de la classe Connect par le code de l'exemple.

Voir aussi

Tâches

Comment : gérer des événements Automation (Visual Basic)

Référence

+=, opérateur (référence C#)

Autres ressources

Réponse aux événements d'automation

Réponse aux événements (projets Visual Basic et Visual C#)