Compartilhar via


Como: consumir eventos em um aplicativo do Windows Forms

Um cenário comum em aplicativos do Windows Forms é exibir um formulário com controles e, em seguida, executar uma ação específica com base no controle em que o usuário clica. Por exemplo, um controle Button gera um evento quando o usuário clica nele no formulário. Ao manipular o evento, seu aplicativo pode executar a lógica apropriada do aplicativo apropriado para esse clique.

Para mais informações sobre o Windows Forms, veja Introdução ao Windows Forms.

Para tratar um evento de clique em um Windows Form

  1. Crie um Windows Form que tenha um controle Button.

    Private WithEvents myButton As Button
    
    private Button button;
    
    private:
        Button^ button;
    
  2. Defina um manipulador de eventos que corresponda à assinatura Click do representante de eventos . O evento Click usa a classe EventHandler para o tipo representante e a classe EventArgs para os dados do evento.

    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. Adicione o método manipulador de eventos para o evento Click do botão .

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

    Dica

    Um designer (como Visual Studio 2005) fará essa fiação de evento para você gerando um código similar ao código nesse exemplo.

Exemplo

O seguinte exemplo de código manipula o evento Click de um Button para alterar a cor do plano de fundo de uma TextBox . Os elementos em negrito mostram o manipulador de eventos e como ele está conectado ao evento Click do Button .

O código nesse exemplo foi escrito sem usar um designer visual (como Visual Studio 2005) e contém apenas elementos essenciais de programação. Se você usar um designer, ele irá gerar código adicional.

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

Compilando o código

Salve o código anterior para um arquivo (com extensão. cs para um arquivo C# e .vb para Visual Basic 2005, compile e execute. Por exemplo, se o arquivo de origem for chamado WinEvents.cs (ou WinEvents.vb), execute o seguinte comando:

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

O arquivo executável será denominado WinEvents.exe.

Consulte também

Conceitos

Delegados e eventos

Consumindo eventos

Disparar um evento

Outros recursos

Tratamento e disparada de eventos