Share via


Comment : consommer des événements dans une application Windows Forms

Un scénario courant dans les applications Windows Forms est d'afficher un formulaire proposant des contrôles, puis d'exécuter une action spécifique selon le contrôle sur lequel l'utilisateur clique. Par exemple, un contrôle Button déclenche un événement lorsque l'utilisateur clique dessus dans le formulaire. En gérant l'événement, votre application peut exécuter la logique d'application appropriée à un clic sur ce bouton.

Pour plus d'informations sur les Windows Forms, consultez Mise en route des Windows Forms.

Pour gérer un événement associé à un clic sur un bouton dans un formulaire Windows

  1. Créez un formulaire Windows contenant un contrôle Button.

    Private WithEvents myButton As Button
    
    private Button button;
    
    private:
        Button^ button;
    
  2. Définissez un gestionnaire d'événements qui correspond à la signature du délégué d'événement Click. L'événement Click utilise la classe EventHandler pour le type délégué et la classe EventArgs pour les données d'événement.

    Private Sub Button_Click(sender As Object, e As EventArgs)
        '...
    End Sub
    
    private void Button_Click(object sender, EventArgs e)
    {
        //...
    }
    
    private:
        void Button_Click(Object^ sender, EventArgs^ e)
        {
            //...
        }
    
  3. Ajoutez la méthode de gestionnaire d'événements à l'événement Click du Button.

    AddHandler myButton.Click, AddressOf Me.Button_Click
    
    button.Click += new EventHandler(this.Button_Click);
    
    button->Click += gcnew EventHandler(this, &SnippetForm::Button_Click);
    

    Notes

    Un concepteur (tel que Visual Studio 2005) assure pour vous la transmission de cet événement en générant un code similaire à celui de cet exemple.

Exemple

L'exemple de code suivant gère l'événement Click d'un Button pour changer la couleur d'arrière-plan de TextBox. Les éléments en gras indiquent le gestionnaire d'événements et son mode de connexion à l'événement Click de Button.

Le code figurant dans cet exemple a été écrit sans utiliser de concepteur visuel (tel que Visual Studio 2005) et ne contient que des éléments de programmation essentiels. Si vous utilisez un concepteur, il générera alors du code supplémentaire.

Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing

Public Class MyForm
    Inherits Form
    Private box As TextBox
    Private WithEvents myButton As Button

    Public Sub New()
        box = New TextBox()
        box.BackColor = System.Drawing.Color.Cyan
        box.Size = New Size(100, 100)
        box.Location = New Point(50, 50)
        box.Text = "Hello"

        myButton = New Button()
        myButton.Location = New Point(50, 100)
        myButton.Text = "Click Me"

        AddHandler myButton.Click, AddressOf Me.Button_Click

        Controls.Add(box)
        Controls.Add(myButton)
    End Sub

    ' The event handler.
    Private Sub Button_Click(sender As Object, e As EventArgs)
        box.BackColor = System.Drawing.Color.Green
    End Sub

    ' The STAThreadAttribute indicates that Windows Forms uses the
    ' single-threaded apartment model.
    <STAThread> _
    Public Shared Sub Main()
        Application.Run(New MyForm())
    End Sub
End Class
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;

public class MyForm : Form
{
    private TextBox box;
    private Button button;

    public MyForm() : base()
    {
        box = new TextBox();
        box.BackColor = System.Drawing.Color.Cyan;
        box.Size = new Size(100,100);
        box.Location = new Point(50,50);
        box.Text = "Hello";

        button = new Button();
        button.Location = new Point(50,100);
        button.Text = "Click Me";

        // To wire the event, create
        // a delegate instance and add it to the Click event.
        button.Click += new EventHandler(this.Button_Click);
        Controls.Add(box);
        Controls.Add(button);
    }

    // The event handler.
    private void Button_Click(object sender, EventArgs e)
    {
        box.BackColor = System.Drawing.Color.Green;
    }

    // The STAThreadAttribute indicates that Windows Forms uses the
    // single-threaded apartment model.
    [STAThread]
    public static void Main()
    {
        Application.Run(new MyForm());
    }
}
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;

public ref class MyForm : Form
{
private:
    TextBox^ box;
    Button^ button;

public:
    MyForm() : Form()
    {
        box = gcnew TextBox();
        box->BackColor = System::Drawing::Color::Cyan;
        box->Size = System::Drawing::Size(100,100);
        box->Location = System::Drawing::Point(50,50);
        box->Text = "Hello";

        button = gcnew Button();
        button->Location = System::Drawing::Point(50,100);
        button->Text = "Click Me";

        // To wire the event, create
        // a delegate instance and add it to the Click event.
        button->Click += gcnew EventHandler(this, &MyForm::Button_Click);
        Controls->Add(box);
        Controls->Add(button);
    }

private:
    // The event handler.
    void Button_Click(Object^ sender, EventArgs^ e)
    {
        box->BackColor = System::Drawing::Color::Green;
    }

    // The STAThreadAttribute indicates that Windows Forms uses the
    // single-threaded apartment model.
public:
    [STAThread]
    static void Main()
    {
        Application::Run(gcnew MyForm());
    }
};

int main()
{
    MyForm::Main();
}

Compilation du code

Enregistrez le code précédent dans un fichier (avec une extension .cs pour un fichier C# et .vb pour un fichier Visual Basic 2005), compilez et exécutez. Par exemple, si le fichier source s'appelle WinEvents.cs (ou WinEvents.vb), exécutez la commande suivante :

vbc /r:System.DLL /r:System.Windows.Forms.dll /r:System.Drawing.dll WinEvents.vb
csc /r:System.DLL /r:System.Windows.Forms.dll /r:System.Drawing.dll WinEvents.vb
cl /clr:pure WinEvents.cpp

Votre fichier exécutable s'appellera WinEvents.exe.

Voir aussi

Concepts

Événements et délégués

Consommation d'événements

Déclenchement d'un événement

Autres ressources

Gestion et déclenchement d'événements