Before you can use object level events you must create a new class module and declare an object of type AcadObject with events. For example, assume that a new class module is created and called EventClassModule. The new class module contains the declaration of the application with the VBA keyword WithEvents.
To create a new class and declare a Circle object with events
Public WithEvents Object As AcadCircle
After the new object has been declared with events, it appears in the Object drop-down list box in the class module, and you can write event procedures for the new object in the class module. (When you select the new object in the Object box, the valid events for that object are listed in the Procedure drop-down list box.)
Before the procedures will run, however, you must connect the declared object in the class module with the Circle object. You can do this with the following code from any module.
To connect the declared object to the Automation object
Dim X As New EventClassModule
Sub InitializeEvents()
Dim MyCircle As AcadCircle
Dim centerPoint(0 To 2) As Double
Dim radius As Double
centerPoint(0) = 0#: centerPoint(1) = 0#: centerPoint(2) = 0#
radius = 5#
Set MyCircle = ThisDrawing.ModelSpace.AddCircle(centerPoint, radius)
Set X.Object = MyCircle
End Sub
Call InitializeEvents
Once the InitializeEvents procedure has been run, the Circle object in the class module points to the Circle object created, and any event procedures in the class module will run when the events occur.
This example creates a lightweight polyline with events. The event handler for the polyline then displays the new area whenever the polyline is changed. To trigger the event, simply change the size of the polyline in AutoCAD. Remember that you must run the CreatePLineWithEvents subroutine before the event handler is activated.
Public WithEvents PLine As AcadLWPolyline
Sub CreatePLineWithEvents()
' This example creates a light weight polyline
Dim points(0 To 9) As Double
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 3
points(8) = 3: points(9) = 2
Set PLine = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
PLine.Closed = True
ThisDrawing.Application.ZoomAll
End Sub
Private Sub PLine_Modified _
(ByVal pObject As AutoCAD.IAcadObject)
' This event is triggered when the polyline is resized.
' If the polyline is deleted the modified event is still
' triggered, so we use the error handler to avoid
' reading data from a deleted object.
On Error GoTo ERRORHANDLER
MsgBox "The area of " & pObject.ObjectName & " is: " _
& pObject.Area
Exit Sub
ERRORHANDLER:
MsgBox Err.Description
End Sub