Generic events
using System;
class MyEventArgs : EventArgs {
public int eventnum;
}
delegate void MyEventHandler<T, V>(T source, V args);
class MyEvent {
static int count = 0;
public event MyEventHandler<MyEvent, MyEventArgs> SomeEvent;
public void OnSomeEvent() {
MyEventArgs arg = new MyEventArgs();
if(SomeEvent != null) {
arg.eventnum = count++;
SomeEvent(this, arg);
}
}
}
class KeyBorardEventHandler {
public void handler<T, V>(T source, V arg) where V : MyEventArgs {
Console.WriteLine("Event " + arg.eventnum +
" received by an KeyBorardEventHandler object.");
Console.WriteLine("Source is " + source);
Console.WriteLine();
}
}
class MouseEventHandler {
public void handler<T,V>(T source, V arg) where V : MyEventArgs {
Console.WriteLine("Event " + arg.eventnum +
" received by a MouseEventHandler object.");
Console.WriteLine("Source is " + source);
Console.WriteLine();
}
}
class UseGenericEventDelegate {
public static void Main() {
KeyBorardEventHandler ob1 = new KeyBorardEventHandler();
MouseEventHandler ob2 = new MouseEventHandler();
MyEvent evt = new MyEvent();
// Add handler() to the event list.
evt.SomeEvent += ob1.handler;
evt.SomeEvent += ob2.handler;
// Fire the event.
evt.OnSomeEvent();
evt.OnSomeEvent();
}
}
Event 0 received by an KeyBorardEventHandler object.
Source is MyEvent
Event 0 received by a MouseEventHandler object.
Source is MyEvent
Event 1 received by an KeyBorardEventHandler object.
Source is MyEvent
Event 1 received by a MouseEventHandler object.
Source is MyEvent
Get event source from event arguments
using System;
using System.Windows.Forms;
using System.Drawing;
class GetEventSourceFromEventArguments : Form {
Button MyButton = new Button();
public GetEventSourceFromEventArguments() {
Text = "Respond to a Button";
MyButton = new Button();
MyButton.Text = "Press Here";
MyButton.Location = new Point(100, 200);
// Add button event handler to list.
MyButton.Click += MyButtonClick;
Controls.Add(MyButton);
}
[STAThread]
public static void Main() {
GetEventSourceFromEventArguments skel = new GetEventSourceFromEventArguments();
Application.Run(skel);
}
// Handler for MyButton.
protected void MyButtonClick(object who, EventArgs e) {
Button b = (Button) who;
if(b.Top == 200)
b.Location = new Point(10, 10);
else
b.Location = new Point(100, 200);
}
}