HOW TO:將事件處理常式方法連接到事件

若要使用在另一個類別 (Class) 中所定義的事件,您必須定義並註冊事件處理常式。 事件處理常式必須和事件所宣告委派 (Delegate) 有著相同的方法簽章。 將處理常式加入至事件,即可註冊事件處理常式。 在將事件處理常式加入至事件後,每當類別引發事件時就會呼叫此方法。

如需說明引發和處理事件的完整範例,請參閱 HOW TO:引發和使用事件

若要加入事件的事件處理常式方法

  • 以和事件委派 (Delegate) 相同的簽章,定義事件處理常式方法。
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. 使用對事件處理常式方法的參考,建立委派 (Delegate) 的執行個體。 呼叫委派執行個體時,會依次呼叫事件處理常式方法。
' 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. 將委派執行個體加入至事件。 引發事件時,會呼叫委派執行個體和相關聯的事件處理常式方法。
' 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;

請參閱

工作

HOW TO:引發和使用事件

概念

使用事件

引發事件

事件和委派

其他資源

處理和引發事件