Declaring and Raising Events

Standalone class modules automatically support two events: Initialize and Terminate. Use the Initialize event to give the variables in your classes initial values. The Initialize event is called when you make a new instance of a class. The Terminate event is called when you set the instance to Nothing.

In addition to these default events, you can define custom events for your class module. To create a custom event, use the Event statement in the declaration section of a class module. For example, the following statement declares an event named SendFlowers that requires two arguments:

Public Event SendFlowers(ByVal strName As String, cancel As Boolean)

The Event statement declares a user-defined event. This statement is followed by the name of the event and any arguments that will be passed to the event procedure. Arguments are separated by commas. An event can have ByVal and ByRef arguments. Recall that when passing the variable ByRef, you are

Part IV

actually passing the memory location of the variable. If you pass a variable ByVal, you are sending the copy of the variable.

When declaring events with arguments, bear in mind that events cannot have named arguments, optional arguments, or ParamArray arguments. The Public keyword is optional as events are public by default.

Use the RaiseEvent statement to fire the event. This is usually done by creating a method in a class module. For example, here's how you could trigger the SendFlowers event:

Public Sub Dispatch(ByVal toWhom As String, cancel As Boolean)

RaiseEvent SendFlowers(toWhom, True) End Sub

Events can only be raised in the module in which they are declared using the Event statement. After declaring the event and writing the method that will be used for raising the event, you need to switch to the form class module and perform the following tasks:

Declare a module-level variable of the class type using the WithEvents keyword

Assign an instance of the class containing the event to the object defined using the WithEvents statement

■ Write a procedure that calls the class method

■ Write the event handler code

The next hands-on demonstrates how a user-defined event can be used in a class. We will learn how to raise the SendFlowers event from a Microsoft Access form.

© Hands-On 27-2: Declaring and Raising Events

1. Activate the Visual Basic Editor window and choose Insert | Class Module. A new class named Class1 will appear in the Project Explorer window.

2. In the Properties window, click the (Name) property and type cDispatch as the new name of Class1. Click again on the (Name) property to save the new name. You should see the cDispatch entry under the Class Modules folder in the Project Explorer.

3. In the cDispatch class module's Code window, enter the following code:

Public Event SendFlowers(ByVal strName As String, _ cancel As Boolean)

Sub Dispatch(ByVal ToWhom As String, cancel As Boolean) If ToWhom = "Julitta" Then cancel = True

MsgBox "Dispatch to " & ToWhom & " was cancelled.", _ vbInformation + vbOKOnly, "Reason Unknown"


RaiseEvent SendFlowers(ToWhom, True) End If End Sub

Event Programming in Forms and Reports

The first statement in the code above declares a custom event called SendFlowers. This event will accept two arguments: the name of the person to whom flowers should be sent and a Boolean value of True or False that will allow you to cancel the event if necessary.

Next, the Dispatch procedure is used as a class method. The code states that the flowers should be sent to the person whose name is passed in the ToWhom argument as long as the person's name is not "Julitta." The RaiseEvent statement will call the event handler that we will write in a form module in a later step.

Create a new form as shown in Figure 27-10. Notice that this form isn't bound to any data source. Set the Name property of the text box control to Recipient and the Name property of the command button to cmdFlowers. Save this form as frmFlowers.

Figure 27-10: The frmFlowers form is used in Hands-On 27-2 to demonstrate the process of raising and handling custom events.

Figure 27-10: The frmFlowers form is used in Hands-On 27-2 to demonstrate the process of raising and handling custom events.

5. While the frmFlowers form is in Design view, choose View | Code.

6. Enter the following code in the Form_frmFlowers Code window: Private WithEvents clsDispatch As cDispatch

Private Sub Form_Load()

Set clsDispatch = New cDispatch End Sub

Private Sub Form_Close()

Set clsDispatch = Nothing End Sub

Our form class can only respond to events from an object if it has a reference to that object. Therefore, at the top of the form class module we declare the object variable clsDispatch by using the WithEvents keyword. This means that from now on the instance of the cDispatch class is associated with events.

The next step involves setting the object variable to an object. In the Form_Load event procedure we create a class object with the Set statement and the New keyword.

Part IV

When the object variable is no longer needed, we release the reference to the object by setting the object variable to Nothing (see the Form_Close event procedure above).

Now that we are done with declaring, setting, and resetting the object variable, let's proceed to write some code that will allow us to raise the SendFlowers event when we click on the Send Flowers button.

7. In the Form_frmFlowers Code window, enter the following Click event procedure for the cmdFlowers command button that you placed on the frmFlowers form:

Private Sub cmdFlowers_Click() If Len(Me.Recipient) > 0 Then clsDispatch.Dispatch Me.Recipient, False Else

MsgBox "Please specify the recipient name." Me.Recipient.SetFocus Exit Sub End If End Sub

Notice that the above event procedure begins by checking whether the user has entered data in the Recipient text box. If the data exists, the Dispatch method is called; otherwise, the user is asked to enter data in the text box. When calling the Dispatch method we must provide two arguments that this method expects: the name of the recipient and the value for the Boolean variable Cancel. Recall that the Dispatch method has the necessary code that raises the SendFlowers event (see step 3 earlier). Now what's left to do is to write an event handler for the SendFlowers event.

8. Select the clsDispatch variable from the object drop-down list in the upper-left corner of the Form_frmFlowers Code window. As you make this selection, a template of the event procedure will be inserted into the Code window as shown below:

Private Sub clsDispatch_SendFlowers(ByVal strName As String, cancel As Boolean) End Sub

The code that you write within the above procedure stub will be executed when the event is generated by the object.

9. Enter the following statement inside the clsDispatch_SendFlowers procedure stub:

MsgBox "Flowers will be sent to " & strName & ".", , "Order taken"

Our custom event is not overly exciting but should give you an understanding of how custom events are declared and raised in a standalone class module and how they are consumed in a client application (form class module).

Event Programming in Forms and Reports

The complete code we entered in the form class module is pictured in Figure 27-11.

Sj Acc2003_Chap27 - Form^frmRawers (Code)


| (General)

t | i (Declarations)


Option Compare Database

[Private UlchEvents clsPl3Datch As cDispach


Private Sub e1sDispateh_SendFlowers (ByVal strName As String, _

cancel As Boolean) HsgBox "Flowers will be sent to " £ strNnroe & ".", , _ "Order taken"

End Sub

Private Sub cmdFlowers Click ()

it Len(He.Recipient) > □ Then clsDispatch.Dispatch He.Recipient, False Else

HscjBox "Please specify the recipient name." He.Recipient.SetFocus Exit Sub End If End Sub

Private Set End Sub

Sub Form_Closei) clsDispatch w Nothing

Private Set End Sub

Sub Form_Load(j clsDispatch = New cDispatch

5a 1


Figure 27-11: The form class module shows code that uses a custom object with its events.

10. To test the code, open the frmFlowers form in Form view, type any name in the Recipient text box, and click the Send Flowers button. You should see the message generated by the SendFlowers custom event. Also see what happens when you type my name (Julitta) in the text box.

Note: If you need more practice declaring and raising custom events, there's an additional example in the Acc2003Chap_27 database. You will find there the default Class1 class module with the Splash event that displays a splash screen when a form is loaded. Also, be sure to try out the example provided in the online help in the RaiseEvent statement topic. The quickest way to find this example is by positioning the cursor in the RaiseEvent statement (located in the cDispatch class module) and pressing F1.

Part IV

0 0


  • kristian
    Which statement declares an event procedure?
    7 years ago

Post a comment