Partager via


Visual Basic Concepts

Adding Code for Initialize and Terminate Events

Class modules have two built-in events: Initialize and Terminate. The code you place in the Initialize event procedure is the first code executed when the object is created, before any properties are set or any methods are executed.

The code you place in the Terminate event is executed when all references to the object have been released, and the object is about to be destroyed.

The following procedure adds code to support the DebugID property, and Debug.Print methods that will display the object’s properties when it’s being created and destroyed.

Note   This topic is part of a series that walks you through creating a sample ActiveX DLL. It begins with the topic Creating an ActiveX DLL.

To add code to the Initialize and Terminate events of the Thing class

  1. In the Object box of the Thing class module, select Class. The Initialize event appears in the Procedure box, and the Code window displays the code template for the event procedure. Add the following code to the event procedure:

    Private Sub Class_Initialize()
       ' Get a debug ID number that can be returned by
       '   the read-only DebugID property.
       mlngDebugID = GetDebugID
       Debug.Print "Initialize Thing " & DebugID _
          & ", Name=" & Name
    End Sub
    
  2. In the Procedure box of the class module, select Terminate. Add the following code to the event procedure:

    Private Sub Class_Terminate()
       On Error Resume Next
       Debug.Print "Terminate Thing " & DebugID _
          & ", Name=" & Name
    End Sub
    

    Important   You should always handle errors in the Class_Terminate event procedure. Errors in Class_Terminate cannot be handled by applications that use your component, and will therefore be fatal to the application.

    By contrast, unhandled errors in the Initialize event are raised at the point where the application created the object, and thus can be handled by the application.

Normally, the Initialize event procedure contains any code that needs to be executed at the moment the object is created, such as providing the time stamp for the DebugID property. The Terminate event contains any clean-up code you need to execute when the object is being destroyed.

Important   The Initialize and Terminate events should never interact with the user. For demonstration purposes, this example uses the two events to give you a visual indication that a Thing object is being created or destroyed.

For More Information   See "Coding Robust Initialize and Terminate Events" in "General Principles of Component Design."

Step by Step

This topic is part of a series that walks you through creating a sample ActiveX DLL.

To See
Go to the next step Creating the TestThing Test Project
Start from the beginning Creating an ActiveX DLL.