Saturday, April 26, 2008

Call Event Handler Function Directly [.Net, WIndowsForms]

When you code Windows Forms application using Visual Studio (VS), your event handling function are generated automatically. Things are handled visually.

But let's say you have made a Menu and make it's event handler function using VS and you want make a toolbar that do the same function. Since you hate recoding everything, you'd like to call the previous event handling function on the menu directly.

It's quite easy when you understand what those parameters generated in event handling function is for. Well, assuming you don't have time to read C# book from the beginning and you need to start coding C# right after you code C++ or Java with tight deadline ahead, you just try to make sense of the code at the spot.

Generally, those function would looks like below :

private void eventHandlingFunction(object sender, EventArgs e)

It turn out that the two parameter above is

  • object sender : the object from which you call this function.
  • EventArgs e : stuff related to what's going on when this function is being called.
So, if you want to call them directly, just pass those two with whatever you see fit. Many times, I usually find that I just need to fill the first arg with "this" and the second one with "EventArgs.Empty", basically saying that :
  • "I (the form that own this funtion) call this myself " and
  • "There's nothing specific going on (that you need to know), I just need you to do the routine"
So, that's it, in simple situation you can just call

eventHandlingFunction(this, EventArgs.Empty);

Of course, you need to make the internal of the function can handle the situation with that kind of argument otherwise the caller need to provide a minimum necessary argument e.g: not just EventArgs.Empty, to get the function running.

No comments: