Sinking Events in Standalone Class Modules

Instead of writing your event procedures in the form and report class modules, you can make the maintenance of your Microsoft Access applications much simpler by writing the event code in standalone class modules.

Recall that a standalone class module is a special type of a class module that is not associated with any particular form or a report. This class module can be inserted in the Visual Basic Editor window by choosing Insert | Class Module. In addition to creating custom objects (see examples in Chapter 8), standalone class modules can implement object events.

The process of listening to an object's events is called sinking the event. To sink (handle) events in a standalone class module you must use the WithEvents keyword. This keyword will tell the class that you want to sink some or all of the object's events in the class module. You determine which events you want to sink by writing appropriate event code (see Custom Project 27-1). Only classes can sink events. Therefore, the WithEvents keyword can only be used in classes. You can use the WithEvents keyword to declare as many individual variables as you need; however, you cannot create arrays using WithEvents.

An object that generates events is called an event source. The process of broadcasting an event is called sourcing the event. To handle events raised by an event source you must declare an object variable using the WithEvents keyword. For example, to react to form events in a standalone class module, you would need to enter the following module-level variable declaration in the class module:

Private WithEvents m_frm As Access.Form

In the above statement, m_frm is the name of the object variable that references the Form object. While you can use any variable name you want, this variable cannot be a generic object. That means you cannot declare it as Object. If the variable were declared as Object, Visual Basic wouldn't know what type library should be used. Therefore, it would not be able to provide you with the names of events that you can write code for.

Now, let's walk through these new concepts step by step. Custom Project 27-1 demonstrates how to create a record logger class that handles a form's AfterUpdate event. Each time the AfterUpdate event occurs, this class will enter information about the newly created record into a text file. With minor modifications, this class will use the same event code that was introduced in Hands-On 24-5 (Chapter 24).

0 0

Post a comment