クラスのイベントハンドラーを定義する
クラスのイベントハンドラーを定義する
クラスでイベントを発生させた時その通知を受け取るための処理を行う必要があります。
この時に受け取り手となるのがイベントハンドラーです。
まずはじめにイベントハンドラーとなるメソッドをあらかじめ定義したdelegate型にそった形で作成します。
イベント名 += デリゲート名(イベントハンドラー);
次に+=演算子を使用してイベントにイベントハンドラーを追加します。
以上の手順によりイベント通知を受け取ります。
namespace WindowsFormsApplication1 { public partial class Form1 : Form { Sample sampleClass = new Sample(); public Form1() { InitializeComponent(); } private void sampleClassEvent(string msg) { MessageBox.Show(msg); } private void button1_Click(object sender, EventArgs e) { if (!sampleClass.Start) { sampleClass.Start = true; sampleClass.sampleEvent += new sampleDelegate(sampleClassEvent); } sampleClass.sampleMethod(); } } public delegate void sampleDelegate(string arg); public class Sample { public event sampleDelegate sampleEvent; private char msg = 'a'; private Boolean start = false; public Boolean Start { get { return this.start; } set { this.start = value; } } public void sampleMethod() { msg++; sampleEvent(msg.ToString()); } } }