Como: Conectar os métodos do manipulador de eventos a eventos

Para consumir eventos definidos em outra classe, você deve definir e registrar um manipulador de eventos. O manipulador de eventos deve ter a mesma assinatura do método como representante declarado para o evento. Você registra seu manipulador de eventos adicionando o manipulador ao evento. Depois de adicionar o manipulador de eventos ao evento, o método é chamado sempre que a classe gera o evento.

Para obter um exemplo completo que ilustra o surgimento e a manipulação de eventos, consulte como: Gerar e consumir eventos.

Para adicionar um método manipulador de eventos a um evento

  • Defina um método manipulador de eventos com a mesma assinatura como o representante de eventos.
Public Class WakeMeUp
    ' AlarmRang has the same signature as AlarmEventHandler.
    Public Sub AlarmRang(sender As Object, e As AlarmEventArgs)
        '...
    End Sub
    '...
End Class
public class WakeMeUp
{
    // AlarmRang has the same signature as AlarmEventHandler.
    public void AlarmRang(object sender, AlarmEventArgs e)
    {
        //...
    }
    //...
}
public ref class WakeMeUp
{
public:
    // AlarmRang has the same signature as AlarmEventHandler.
    void AlarmRang(Object^ sender, AlarmEventArgs^ e)
    {
        //...
    }
    //...
};
  1. Crie uma instância do representante, usando uma referência para o método manipulador de eventos. Quando a instância do representante é chamada, em sua vez ele chama a método manipulador de eventos.
' Create an instance of WakeMeUp.
Dim w As New WakeMeUp()

' Instantiate the event delegate.
Dim alhandler As AlarmEventHandler = AddressOf w.AlarmRang
// Create an instance of WakeMeUp.
WakeMeUp w = new WakeMeUp();

// Instantiate the event delegate.
AlarmEventHandler alhandler = new AlarmEventHandler(w.AlarmRang);
// Create an instance of WakeMeUp.
WakeMeUp^ w = gcnew WakeMeUp();

// Instantiate the event delegate.
AlarmEventHandler^ alhandler = gcnew AlarmEventHandler(w, &WakeMeUp::AlarmRang);
  1. Adicione a instância do representante ao evento. Quando o evento é gerado, a instância do representante e seus métodos manipuladores de eventos associados são chamados.
' Instantiate the event source.
Dim clock As New AlarmClock()

' Add the delegate instance to the event.
AddHandler clock.Alarm, alhandler
// Instantiate the event source.
AlarmClock clock = new AlarmClock();

// Add the delegate instance to the event.
clock.Alarm += alhandler;
// Instantiate the event source.
AlarmClock^ clock = gcnew AlarmClock();

// Add the delegate instance to the event.
clock->Alarm += alhandler;

Consulte também

Tarefas

Como: Gerar e consumir eventos

Conceitos

Consumindo Eventos

Gerando um evento

Eventos e representantes

Outros recursos

Tratamento e disparada de eventos