The life of an ordinary Visual Basic form is marked by certain key events, such as Initialize, Load, QueryUnload, and Unload. In order to create well-behaved applications, it’s important to know when these events occur in the life cycle of a form.
Although ActiveX documents look like forms, they behave differently, primarily because they are contained by another application. When programming an ActiveX document, some attention must be given to the ephemeral nature of an ActiveX document. This is especially true when the container application is a Web browser, such as Internet Explorer.
Key events in the life cycle of a UserDocument object include Initialize, InitProperties, Show, Hide, and Terminate. The following procedure demonstrates these events.
Note This topic is part of a series that walks you through creating a sample ActiveX control. It begins with the topic Creating an ActiveX Document.
To observe the key events of the FirstDoc UserDocument
Private Sub UserDocument_Initialize()
Debug.Print "Initialize"
End Sub
Private Sub UserDocument_InitProperties()
Debug.Print "InitProperties"
End Sub
Private Sub UserDocument_Show()
Static intCount As Integer
intCount = intCount + 1
Debug.Print "Show " & intCount
End Sub
Private Sub UserDocument_Hide()
Static intCount As Integer
intCount = intCount + 1
Debug.Print "Hide " & intCount
End Sub
Private Sub UserDocument_Terminate()
Debug.Print "Terminate"
End Sub
Note You will notice that Show is followed by a 1, indicating that the ActiveX document has been shown once by Internet Explorer. As long as a reference to the ActiveX document exists in the Internet Explorer cache, this number will increment once each time you navigate to the ActiveX document from another URL.
The Initialize and InitProperties events have some similarities, but you should be aware of how they differ. In brief, the Initialize event always occurs when the ActiveX document is loaded, while InitProperties will only occur every time until the document is saved. After that event has fired, the ReadProperties and WriteProperties events will fire. To see an example of this:
You should note this behavior, as it impacts where you place your code. Needless to say, if you always want a procedure to run on startup, you should put it into the Initialize event. If you want a procedure to run only the first time a user views your ActiveX document, place it in the InitProperties event.
You should be cautious, however, about the limitations of using the Initialize event. In brief, any procedures that require knowledge of the container (such as the Parent property) are unavailable when the Initialize event occurs. An alternate event that occurs after the ActiveX document has been sited in the container is the Show event.