When a piece of software responds to an external event, such as a mouse clicking on a button, a game controller pressed in a game, a key pressed on a keyboard, or the tick of the system clock, the subroutine that responds to that event is called an event handler.
For example, imagine a Windows application with nothing but an “OK” button in it. When you click it, it displays a message box with “Hello” in it.
Here’s what the event handler code looks like for the “OK” button on the window titled “Form1” above: (this is C# code)
Code Snippet
- private void OKButton_Click(object sender, EventArgs e)
- {
- MessageBox.Show(“Hello”);
- }
Any subroutine of code that is automatically triggered by a user or machine initiated event is called an event handler.