Attaching an Event Procedure to a Form or Control


The code you attach to a form5272EF or controlXX9KJT is called an event procedureDZ1BTO.  Every form and control has a set of predefined events1L2S0SZ that it can recognize.  You attach event procedures only for events to which you want a form or control to respond.

To attach an event procedure to a form or control

   1. Double-click a blank part of the form to open the form's Code windowJ73QNY.  To attach code to a control, double-click the control.

   2. In the Procedure boxBK0DPM, select the event to which you want to attach code.

   3. Enter the code you want in the template1KTWQTC provided, following guidelines for entering and editing code5SZA0GX and declarations1AS3HT9.

   4. Repeat steps 2 and 3 as necessary to attach additional event procedures to the item.


Use this syntax when writing an event procedure:

Sub ItemName_EventName (arguments)

          local variable and constant definitions


End Sub


Note   When attaching an event procedure, you can also select a form or control from the Object box in the Code window.  The information displayed in the Procedure box then changes to reflect the predefined events for the object you have selected.  Bold text in the Procedure box indicates event procedures for which you have written code.

Instead of using the template provided for you by Visual Basic, you can also create a new procedure by typing Sub ProcedureName in the Code window.

If you change the Name property of a control after attaching a procedure to it, you must also change the name of the procedure to match the name of the control.  Otherwise, Visual Basic won't be able to match the control to the procedure.  You can find the procedure by selecting (general) from the Code window's Object box and then selecting the procedure from the Procedure box.

For a list of the events that apply to forms and each type of control, see the topics under the Properties, Events, and Programming Language indexes10QYEUI.  For a list of all Visual Basic events, see the Events indexC6JZLS.


See Also


Creating a General Procedure1IPNOPP


Learning Visual Basic:

Writing Event-Driven Programs


Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"