The Windows applications created by C# programmer will always do more or less the same job:
- Accept an input from a user
- Carry out some processing or calculations based on that user input
- Display any required results to the user
And all of that is done by using buttons and text boxes, for example the programmer may produce a C# application that:
- Requires the user to type a number into a text box
- The application displays the square root of the number in a label
The programmer has two ways for their application to be aware of the fact that user activities have been carried out:
- Mouse Events – the user clicks on a button with the mouse
- Key Events – the user uses the keyboard to type in data
In either case the programmer monitors what is happening by using an event handler.
Using a C# Event Handler with a Mouse
When a C# programmer adds a button to a form it will not actually do anything. That is, of course, because it will not have any code to run. In order for that to happen the programmer must do two things:
- Add an event handler to the button that will call a function when the button is clicked on by the mouse
- Create a function to be called by the event handler
The event handler is added to the button (or any component) very easily:
Now, if the button “cmdDoCalc” is clicked with the mouse then the function “button_click” will be run. The functions called by the event handler must have the same general format:
In this example the function called simply calls a second one. The result is that a label is updated with the square root of the number entered into a text box:
In this example the calculation is run only when the button is clicked. However the activities of the form can also be driven by events in other components such as text boxes.
Using a C# Event Handler with the Keyboard
An event handler can be added to objects such as text boxes so that the user’s keystrokes can be monitored and acted upon. Here a function is run whenever a key on the keyboard is released:
Like the mouse event handler, the function being called has its own particular format:
Now the function will be run whenever the user adds a new character into the text box.
Summary
The programmer captures events in a C# form by using event handlers. The event handlers come in two varieties:
- Mouse events
- Keyboard events
Each event handler can be added to a component on a form and then they call a particular function when the event (such as a mouse click or keyboard key press) occurs. By using these the programmer can control all of the activities in their C# application.