Common Capturing of GUI Events






4.54/5 (4 votes)
This tip presents a general method for capturing GUI events.
Introduction
In a GUI, events are used to capture user interactions with the GUI. Some such events are Button clicks, changes to CheckBox state (checked or unchecked), changes in the value of NumericUpDown controls, etc. In many cases, the event associated with any GUI component is handled by an event handler that is unique to a single control. This tip provides an alternative method.
The Usual Method
What usually appears for two Button controls, named some_button and some_other_button, is:
// ***************************************** some_button_Click
void some_button_Click ( object sender,
EventArgs e )
{
// action to take on click of some_button
}
// *********************************** some_other_button_Click
void some_other_button_Click ( object sender,
EventArgs e )
{
// action to take on click of some_other_button
}
The Proposed Method
The event handlers for all instances of a given type of control are combined into one event handler. The trick is to assign different values to the Tag properties of each Button.
For example, if the Tag of the some_button control is specified as "some_button" and the Tag of the some_other_button control is specified as "some_other_button", then the event handler for both Button controls can become:
// ************************************************* BUT_Click
void BUT_Click ( object sender,
EventArgs e )
{
Button button = ( Button ) sender;
string tag = button.Tag.ToString ( ).
ToUpper ( ).
Trim ( ).
Replace ( '_', '-' );
switch ( tag )
{
case "SOME-BUTTON":
// action to take on click of some_button
break;
case "SOME-OTHER-BUTTON":
// action to take on click of some_other_button
break;
default:
throw new ApplicationException (
String.Format (
"{0} is not a recognized Button Tag",
button.Tag.ToString ( ) ) );
}
}
A few notes.
- Tag is an object so its ToString method must be invoked.
- MSDN suggests that comparisons should be made using upper-case.
- The replacement of underscores by hyphens allows for Tags that are not formed in exactly the same way.
- All Tags must be processed within the switch statement. If a Tag for a Button whose Click event handler is defined as a common Click event handler is not processed in the switch statement, an exception will be thrown.
Advantage
This method of handling events in a common event handler has the advantage of placing event handling for a-like controls into one method. In turn, this simplifies code and reduces maintenance efforts.