You can use the Forms Designer to create event handlers. An event handler is a routine in your code that determines the actions to perform when an event occurs, such as the user's clicking a button.
For example, the event handler for the mouseDown event provides a mouseEvent object so you can determine which mouse button was pressed, where the mouse was positioned on the form, and which keys on the keyboard were pressed during the click.
You can add an event handler using the events view in the Properties window. A handler for the default event can also be added by double-clicking. Moreover, you can assign an existing handler to the events of other controls if the signatures of the events are the same.
To add an event handler using the events view in the Properties window
For example, on the Button control, you can select the click event.
The Text editor is displayed showing the code for the form, and an event handler method is generated in your code similar to the following:
private void StartProcess(Object sender, Event e)
{
}
In this example, sender is the source of the event and e is an Event object that provides information about the event.
You can also create event handlers that use the default naming format instead of a name you provide.
To add an event handler using the default event handler name
The Text editor is displayed showing the code for the form, and an event handler method is generated in your code using the format, controlName_eventName. For example, if you have a Button control named button1
on your form and you create an event handler for the click event using the default name, an event handler is created similar to the following:
private void button1_click(Object source, Event e)
{
}
Note Forms and most controls define a default event. The default event is the most commonly handled event for the form or control. To create an event handler for the default event of a form or control, double-click the form or control.
An event handler can be used to handle more than one event for a control. For example, you can create an event handler for the mouseDown event of a form or control and use that same event handler method to handle the mouseUp and mouseMove events. To use the same event handler for multiple events, the events must have event handlers with the same method signature. You can also share event handlers between controls. For example, if you created an event handler for the click event of a Button control named button1
, you can use that same event handler method to handle the click event (or an event with an identical method signature) of a Button control called button2
.
To share an existing event handler with another control
The Properties window provides code in your form that connects the event for the second control to the existing event handler.