[FAQ's: OD] How do I create or handle events in a drawing?
There are times when you may need to capture certain events from Visio so you can intercept, add some processing, logging, security, etc. The WithEvents keyword creates a event handler for the object type that is declared with it. You will have to set a new instance of the event object variable before it can be used.
If you create the event procedures in Visio VBA then you dont need the WithEvents keyword since you are in its environment (the same thread process). Simply pull down the events and let the VBA IDE create them for you.
Here is a basic example of setting up some events to trigger depending on certain actions in Visio.
Visio 2003 VBA
VB Code:
Option Explicit
'Behind ThisDocument
Private Sub Document_BeforeDocumentClose(ByVal doc As IVDocument)
MsgBox "Document About to Close"
End Sub
Private Sub Document_BeforeDocumentSave(ByVal doc As IVDocument)
MsgBox "Document About to be Saved"
End Sub
Private Sub Document_DocumentCloseCanceled(ByVal doc As IVDocument)
MsgBox "Document Closing Canceled"
End Sub
Private Sub Document_DocumentOpened(ByVal doc As IVDocument)
MsgBox "Document Opened"
End Sub
Private Function Document_QueryCancelDocumentClose(ByVal doc As IVDocument) As Boolean
MsgBox "Document Closing About to be Canceled"
End Function
Visio 2003 And VB 6 Code Example
VB Code:
Option Explicit
'Add a reference to MS Visio xx.0 Object Library
'Create an event handler for the document object
Public WithEvents moVsd As Visio.Document
'Create a form level object variable for the application object
Private moApp As Visio.Application
Private Sub Command1_Click()
'Attempt to close the drawing
moVsd.Close
'Cancel the close
moVsd_QueryCancelDocumentClose = True
End Sub
Private Sub Form_Load()
Set moApp = New Visio.Application
'Open the Visio File
Set moVsd = moApp.Documents.Open("C:\Development\Tips\Visio FAQ - Events\Drawing1.vsd")
moApp.Visible = True
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
'Clean up ovject variables
If moVsd Is Nothing Then
moVsd.Close
End If
Set moVsd = Nothing
If moApp Is Nothing Then
moApp.Quit
End If
Set moApp = Nothing
End Sub
'Visio Event Procedures
Private Sub moVsd_BeforeDocumentClose(ByVal doc As Visio.IVDocument)
Me.SetFocus
MsgBox "Document About to Close"
End Sub
Private Sub moVsd_DocumentCloseCanceled(ByVal doc As Visio.IVDocument)
Me.SetFocus
MsgBox "Document Close Canceled"
End Sub
Private Sub moVsd_DocumentSaved(ByVal doc As Visio.IVDocument)
Me.SetFocus
MsgBox "Document Saved"
End Sub
Private Function moVsd_QueryCancelDocumentClose(ByVal doc As Visio.IVDocument) As Boolean
Me.SetFocus
MsgBox "Query Document Close Canceled"
End Function
Private Sub moVsd_ShapeAdded(ByVal Shape As Visio.IVShape)
Me.SetFocus
MsgBox "Shape Added"
End Sub