Using 'With Events' - August 2001

It took me awhile to figure out how to use 'With Events'. The VB documentation is not clear. I could not find any working examples. So I wrote a demo program to learn how to raise events from class modules. I enhanced the demo and have made it the tip-of-the-month. This begins the fifth year of these tips.

The Demo

The demo program uses a class module to calculate prime numbers. The class module raises two events, one returns a prime number and the second raises an event when the range of numbers has been examined.

Calculate Prime Numbers

Starting Number - Enter a starting number to be examined.

Ending Number - Enter an ending number.

Find Prime Numbers - Click this command button to begin examining the range of numbers for primes. The caption changes to 'Stop Lookiing' while numbers are being calculated.

Stop Looking - Interrupt the prime number calculation routine.

Exit - Click this button to end the demo.

How it Works

An instance of the class is defined in the form's declaration section, for example:

Option Explicit
Private WithEvents mobjFindPrimes As clsFindPrimes

The 'WithEvents' declaration causes events defined in the class module to be available in the form, for example:

Private Sub mobjFindPrimes_PrimeNumber(lPrime As Long)
    'lPrime returned after a prime number is found
End Sub

Private Sub mobjFindPrimes_Finished()
    'event fired after the range of number has been examined
End Sub

The object is instantiated to start the process, for example:

Set mobjFindPrimes = New clsFindPrimes 'instantiate the object
mobjFindPrimes.FindPrime Me.Text1(0).Text, Me.Text1(1).Text

Events are defined in the class module, for example:

Option Explicit
Public Event PrimeNumber(lPrime As Long) 'tell them we found one
Public Event Finished() 'tell them we did all that was asked of us

The events are raised in the class module, for example:

If IsPrime(l) Then
    RaiseEvent PrimeNumber(l)
End If

The Demo Program Uses modConnectToWebSite

The demo program uses modConnectToWebSite.bas to display this page. For details on the use of that module click here.

Download VB 6 Source Code

Click here to download the VB 6 source code [6k]

Previous Tip   Tip Index    Next Tip


Updated 2001/09/08