Adding an Event Handler

   

You can use the Forms Designer to create event handlers. An event handler is a routine in your code that determines which 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 that allows you to 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 of the Properties window

  1. Click the control (such as a button control) or form you want an event handler created for.

  2. In the Properties window, click the events view button (indicated by a thunderbolt symbol).

  3. In the list of available events, click an event (for example, click).

  4. In the box to the right of the event name, type the name of the handler (for example, MyButton_click), and press ENTER.

    A code template is generated in your code similar to the following:

    private void MyButton_click(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.

To add a handler for the default event

To use to the same handler for events shared by multiple controls

  1. In the events view in the Properties window, click an event for the first control.

  2. In the box to the right of the event name, type the name of the handler and press ENTER.

  3. On the form, select the second control.

  4. In the Properties window, click the same event for the second control.

  5. Click the drop-down arrow to view a list of existing handlers for this type of event.

  6. Select the name of the event handler. Only the existing handler is used. No new templates are created in the code.