Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Rule 2-4: Avoid the Limitations of Class-Based Events with Custom Callbacks

The notion of events and event handling has been a central feature of VB since its inception. The most common case is graphical user interface (GUI) building, which typically requires the programming of form Load and Unload events, command button Click events, and text box Validate events. But you can also define and raise your own custom, class-based events. For example, the class CConsultant could raise a Changed event whenever one or more data fields in the object are updated:

'** class module CConsultant
Option Explicit

Implements IEmployee

Private sName As String

Public Event Changed() '** event definition: Changed
Private Property Get IEmployee_Name() As String
	IEmployee_Name = sName
End Sub

Private Property Let IEmployee_Name(ByVal sRHS As String)
	sName = sRHS
	RaiseEvent Changed  '** name was changed, so raise event!
End Sub

Any client that holds a reference to a CConsultant object now has the option to handle this event, and thus be notified whenever that employee's data changes:

'** form module denoting client
Option Explicit

Private WithEvents employee As CConsultant '** client reference

Private Sub employee_Changed()       '** event handler
	<update form to reflect change in employee object>
End Sub

In essence, events enable an object to call back to its clients, as shown in Figure 2.12.

Figure 2.12 Events are really just a callback mechanism

Unfortunately, VB's class-based event mechanism has a number of limitations. For the client, the WithEvents key word can be applied only to module-level reference variables; arrays, collections, and local variables are not compatible with events. For the class designer, events must be defined in the class that raises them, preventing you from defining a single set of events for reuse across multiple classes. In particular, this means you cannot incorporate events in your custom interfaces, such as IEmployee:

'** class module IEmployee
Option Explicit

Public Name As String

Public Event Changed() '** unfortunately, this doesn't work...

Public Sub ReadFromDB(rsCurRecord As ADODB.Recordset)
End Sub

Public Function IssuePaycheck() As Currency
End Function

Although VB accepts this event definition, you'll be unable to raise this event from any of your classes.

The solution to these limitations is to design your own event mechanism based on custom interfaces. Consider once again Figure 2.12. Notice that events represent nothing more than an interface implemented by one or more clients. For example, here is a custom interface IEmployeeEvents that defines the Changed event:

'** class module IEmployeeEvents
Option Explicit

Public Sub Changed(rEmp As IEmployee)
End Sub

The difference is that events are represented as ordinary subroutines; in this case, with an explicit parameter providing a reference back to the object for ease of access. To receive events, the client now implements the appropriate interface, such as IEmployeeEvents:

'** form module denoting client
Option Explicit

Implements IEmployeeEvents

Private Sub IEmployeeEvents_Changed(rEmp As IEmployee)
	<update form to reflect change in rEmp.Name, etc.>
End Sub

However, we must mention one little detail: How does the object get that reference back to the client, as shown in Figure 2.12? The object will raise the event by making a call like this: 5

rClient.Changed Me

But who sets this rClient reference variable?

The client does, by calling the object to set up the callback mechanism. Thus, before any events can occur, the client must first call the object and register itself: 6

rObject.Register Me  '** register a reference back to ME, the client 

This means the object must expose a Register method. Likewise, the object should expose an Unregister method so that clients can stop receiving events:

rObject.Unregister Me  '** unregister ME, the client

Because every object that wishes to raise events must provide a means of client registration, the best approach is to define these methods in a custom interface and to reuse this design across all your event-raising classes. The following interface IRegisterClient summarizes this approach:

'** class module IRegisterClient
Option Explicit

Public Enum IRegisterClientErrors
	eIntfNotImplemented = vbObjectError + 8193
End Enum

Public Sub Register(rClient As Object)
End Sub

Public Sub Unregister(rClient As Object)
End Sub

Now, every class that wishes to raise events simply implements IRegisterClient.

As shown in Figure 2.13, the end result is a pair of custom interfaces, IRegisterClient and IEmployeeEvents. The object implements IRegister Client so that a client can register for events, whereas the client implements IEmployeeEvents so the object can call back when the events occur. For completeness, here's the CConsultant class revised to take advantage of our custom event mechanism:

'** class module CConsultant
Option Explicit

Implements IRegisterClient
Implements IEmployee

Private sName As String
Private rMyClient As IEmployeeEvents '** ref back to client

Private Sub IRegisterClient_Register(rClient As Object)
	If Not TypeOf rClient Is IEmployeeEvents Then
		Err.Raise eIntfNotImplemented, ...
	ElseIf Not rMyClient Is Nothing Then
		Err.Raise eAlreadyRegistered, ...
		Set rMyClient = rClient
	End If
End Sub

Private Sub IRegisterClient_Unregister(rClient As Object)
	If Not rMyClient Is rClient Then
		Err.Raise eNotRegistered
		Set rMyClient = Nothing
	End If
End Sub

Private Property Get IEmployee_Name() As String
	IEmployee_Name = sName
End Sub

Private Property Let IEmployee_Name(ByVal sRHS As String)
	sName = sRHS
	On Error Resume Next '** ignore unreachable/problematic clients
	rMyClient.Changed Me '** name was changed, so raise event!
End Sub

Figure 2.13 An event mechanism based on custom interfaces

The first step is to save the client's reference in a private variable (rMyClient) when he registers. Then, whenever we need to raise an event, we simply call the client via this reference. Finally, when the client unregisters, we reset the private variable back to Nothing. Note that the Register and Unregister methods perform error checking to make sure that (1) the client is capable of receiving events, (2) the client is not already registered, and (3) the correct client is being unregistered. Furthermore, to handle multiple clients, also note that the previous approach is easily generalized by replacing rMyClient with a collection of client references.

To complete the example, let's assume on the client side that we have a VB form object that instantiates a number of employee objects (CConsultant, CTechnical, CAdministrative, and so on) and displays them on the screen. The client's first responsibility is to implement the custom IEmployeeEvents interface so it can receive the Changed event:

 '** form module denoting client
Option Explicit

Private colEmployees As New Collection '** collection of object refs

Implements IEmployeeEvents

Private Sub IEmployeeEvents_Changed(rEmp As IEmployee)
	<update form to reflect change in rEmp.Name, etc.>
End Sub

Here the Changed event is used to drive the updating of the form. Before the client can receive these events however, it must register with each employee object that supports "eventing." In this case we assume the employees are created during the form's Load event based on records from a database:

Private Sub Form_Load()
	<open DB and retrieve a RS of employee records>

	Dim rEmp As IEmployee, rObj As IRegisterClient

	Do While Not rsEmployees.EOF
		Set rEmp =CreateObject(rsEmployees("ProgID").Value)

		If TypeOf rEmp Is IRegisterClient Then '** event based
			Set rObj = rEmp  '** switch to register interface...
			rObj.Register Me '** and register myself to receive events
		End If

		rEmp.ReadFromDB rsEmployees
		colEmployees.Add rEmp

	<close DB and RS>
End Sub

Lastly, the client is also responsible for unregistering when it no longer wishes to receive events. This task is performed during form Unload (i.e., when the form is no longer visible):

Private Sub Form_Unload(Cancel As Integer)
	Dim rEmp As IEmployee, rObj As IRegisterClient
	Dim l As Long

	For l = colEmployees.Count To 1 Step -1
		Set rEmp = colEmployees.Item(l)
		colEmployees.Remove l

		If TypeOf rEmp Is IRegisterClient Then '** event based
			Set rObj = rEmp   '** switch to register interface...
			rObj.Unregister Me '** and unregister myself
		End If
	Next l
End Sub

Note that unregistering is important to break the cyclic reference formed between the client and the object.

Although custom callbacks require more effort to set up than VBs built-in event mechanism, the benefits are many: reusable designs, better callback performance, and more flexibility during implementation. 7 For example, an object with multiple clients can apply a priority-based event notification scheme if desired. In the greater scheme of things, custom callbacks also illustrate the power of using interfaces to design flexible solutions to everyday problems.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020