Hi guys, it is my first time posting here in channel9, so please if I made a mistake, please tell me.
I am currentlly learning C#, but I couldn`t understand the Event and the Event Handler, can some one help me with it? I have read the documentation in the library of the C# express edition but I didn't managed to understand it very well.
And thank you in advance.
-
-
The even is an implementation of the observer design pattern. The idea is that you can register for something to happen and once it happens you get informed about that.
In concrete you register an event (is something that happens) of an object instance. And that instance is going to inform you when something happens...
Example:
// First we create an instance of the Button class. This is a normal
// button that can be clicked.
Button btn = new Button();
// Now we register the Click event. That means we get notified each
// time the button got clicked. The btn_Click is a method that is
// going to be called when the button gets clicked.
btn.Click += new EventHandler(btn_Click);
// That's the method that is going to be called.
private void btn_Click(object sender, EventArgs e)
{
// Here we do something with the event.
// For example show a message box.
MessageBox.Show("Hello World!");
}
In the example we registered the Click event. Registering means we told the button to call the method that we provided, when somebody clicked it. The += is just notation: it means that we want to register this method (= have it called when a click happens). There is also -= which would mean that we don't want that method called anymore.
new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:
btn.Click += btn_Click;
You need to encapsulate (wrap) it in a delegate. A delegate is something that points to a method. It holds a method and says: if you call me I'm going to call that method for you. The delegate defines also what arguments that method has: that's required because everything is type-safe in .NET. The general EventHandler delegate defines the method's arguments with object sender, EventArgs e
I hope this helps
-
An event is a call into code that happens when something "happens", like a user clicks or a key is typed or a file is downloaded.
Events provide a mechanism of saying "when" in code, such as "when someone clicks this rectangle, make it blue."
In terms of using someone else's event, I suggest playing with the C# express edition's forms. Inside a form add a button and then go to the code (right-click, view code) add the following
namespace Program
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
this.BackColor = System.Drawing.Color.Blue;
MessageBox.Show("Clicked!");
}
}
}
This says "When button1 is clicked, change the backcolor to blue and provide a notification saying "Clicked"".
Creating your own events is slightly more tricky.
Here is some code that downloads a file asyncronously:
public class DownloadFile
{
private string downloadTo, downloadFrom;
public DownloadFile(string downloadFrom, string downloadTo)
{
this.downloadFrom = downloadFrom;
this.downloadTo = downloadTo;
new System.Threading.Thread(new System.Threading.ThreadStart(dlThread)).Start();
}
void dlThread()
{
new System.Net.WebClient().DownloadFile(downloadFrom, downloadTo);
}
}
Now you might want to be notified when your file is downloaded, so you can add a new event, Downloaded:
public class DownloadFile
{
private string downloadTo, downloadFrom;
public event System.EventHandler<System.EventArgs> Downloaded;
public DownloadFile(string downloadFrom, string downloadTo)
{
this.downloadFrom = downloadFrom;
this.downloadTo = downloadTo;
new System.Threading.Thread(new System.Threading.ThreadStart(dlThread)).Start();
}
void dlThread()
{
new System.Net.WebClient().DownloadFile(downloadFrom, downloadTo);
if(this.Downloaded != null)
this.Downloaded(this, new System.EventArgs());
}
}
The if conditional makes sure that there is something to call, incase you don't care about the Downloaded event.
In the first example you saw that the function that is called from the event has two arguments - this is always an object sender and a second argument which derives from System.EventArgs. This allows you to send additional information back from an event that occurs, such as the coordinates of a mouse-move event or the key that was typed in a keyPress event.
In our example of DownloadFile, you might want to send back the name of the file we downloaded, in case the main program has forgotten it, so we need to add a new class:
public class DownloadFileEventArgs : System.EventArgs
{
private string name;
public string FileName {
get {
return name;
}
}
public DownloadFileEventArgs(string name){
this.name = name;
}
}
and in our class DownloadFile:
public class DownloadFile
{
private string downloadTo, downloadFrom;
public event System.EventHandler<DownloadFileEventArgs> Downloaded;
public DownloadFile(string downloadFrom, string downloadTo)
{
this.downloadFrom = downloadFrom;
this.downloadTo = downloadTo;
new System.Threading.Thread(new System.Threading.ThreadStart(dlThread)).Start();
}
void dlThread()
{
new System.Net.WebClient().DownloadFile(downloadFrom, downloadTo);
if(this.Downloaded != null)
this.Downloaded(this, new DownloadFileEventArgs(downloadTo));
}
}
In our form we can now do this:
public class Form1(){
private DownloadFile;
public Form1(){
InitializeComponents();
string downloadFrom = "http://en.wikipedia.org/images/wiki-en.png";
string desktop = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string downloadTo = desktop + @"\wiki.png";
DownloadFile = new DownloadFile(from, to);
DonwloadFile.Downloaded += new System.EventHandler<DownloadFileEventArgs>(DownloadFile_Downloaded);
}
void DownloadFile_Downloaded(object sender, DownloadFileEventArgs e)
{
MessageBox.Show(String.Format("File {0} downloaded ok!",e.FileName));
}
}
I hope this clears up events in your mind a bit. -
littleguru wrote:new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:
btn.Click += btn_Click;
Um, yes you can in C# 2.0. I use it all the time
It makes the code much cleaner to read.
-
Hello Katana,
You may want to check video3 at the Beginner Developer Learning Center at MSDN. Events are very simple in essence, but the concepts aren't always simple to understand first up.
Ultimately most useful things you will do (program) will be based on an Event in windows so try not to stress yourself if you can't grasp it. After programming a while you'll wonder how you ever misunderstood them. -
Andrew Davey wrote:

littleguru wrote:
new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:
btn.Click += btn_Click;
Um, yes you can in C# 2.0. I use it all the time
It makes the code much cleaner to read.
I didn't know. Nice to know. Thanks!
But: just to make that clear. Internally the compiler is getting the arguments and creating the delegate for you. -
thanx alot guys for the help
, I will check the information that you have gave me and I will see what I can do. -
btw its called delegate inference or method group conversions or whateverlittleguru wrote:
Andrew Davey wrote:

littleguru wrote:
new EventHandler is a delegate. In .NET you can't directly give to the event a method. This doesn't work:
btn.Click += btn_Click;
Um, yes you can in C# 2.0. I use it all the time
It makes the code much cleaner to read.
I didn't know. Nice to know. Thanks!
But: just to make that clear. Internally the compiler is getting the arguments and creating the delegate for you. -
Guys, Can some one give me some examples that runs on the console, I mean without the GUI?
-
public class Program{
private DownloadFile;
public static void main(){
string downloadFrom = "http://en.wikipedia.org/images/wiki-en.png";
string desktop = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string downloadTo = desktop + @"\wiki.png";
DownloadFile = new DownloadFile(from, to);
DonwloadFile.Downloaded += new System.EventHandler<DownloadFileEventArgs>(DownloadFile_Downloaded);
}
void DownloadFile_Downloaded(object sender, DownloadFileEventArgs e)
{
MessageBox.Show(String.Format("File {0} downloaded ok!",e.FileName));
}
} -
This is an example that prints just on each time the timer event fires "Elapsed" on the console:
class Program
{
static void Main(string[] args)
{
// Set up a timer and make it run.
System.Timers.Timer timer = new System.Timers.Timer(1000);
// Tell the timer to call the "timer_Elapsed" method on each time the interval specified
// in the constructor of the timer has been reached.
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
// Start the timer.
timer.Start();// Wait for the user to enter a line (for example press the ENTER key).
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
Console.ReadLine();
}
{
Console.WriteLine("Elapsed");
}
}
You might just copy it into a console application project (replace the Program class there) and run it. -
Maybe it's useful to show a more complete sample containing an event definition as well.
Let's start with the concept of a delegate, which is an object that can point to a method with a given signature:
delegate int BinOp(int a, int b);
BinOp can point to any method that takes two ints and returns an int. For example:
int Add(int a, int b) { return a + b; }
can be pointed at by a BinOp delegate, like this:
BinOp add = new BinOp(Add);
or even (starting from C# 2.0):
BinOp add = Add; //the same as the code above, just more convenient
One can call the target method a delegate is pointing at by using regular method call syntax on the delegate instance, like this:
add(1,2); //notice the casing of add - we're not calling Add directly but through the delegate created above
For the following, consider a delegate defined like this:
delegate void ChangedEventHandler(object o, ChangedEventArgs e);
Note: there's a generic EventHandler class that provides a shortcut to create typical *EventHandler delegates.
Now we can cook up an event using this delegate. This allows users of a class to "subscribe" to an event by pointing at a method with the appropriate signature:
class Controller
{
public event ChangedEventHandler StateChanged; //events have a delegate type, in this case ChangedEventHandler
public void DoWork()
{
//do work
if (StateChanged != null) //make sure someone has subscribed
StateChanged(this, new ChangedEventArgs(...)); //delegate calling syntax
//do more work
}
}
This allows the user of the class to subscribe to the event like this:
Controller ctrl = new Controller();
ctrl.StateChanged += new ChangedEventHandler(ctrl_Changed);
where ctrl_Changed is defined like this:
void ctrl_Changed(object o, ChangedEventArgs e)
{
//do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
}
Or, using anonymous method syntax in C# 2.0 and higher:
Controller ctrl = new Controller();
ctrl.StateChanged += delegate (object o, ChangedEventArgs e)
{
//do something to handle the event; o points at the object that raised the event - you can cast it back to Controller
};
Hope this helps.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.