5.5. Trapping an Automation Server's Events

Most objects raise events, which can be used to great effect in your VB application and add a further dimension to OLE automation. Rather than the usual one-way conversation, in which your application is forever telling the server what to do or asking it to provide information about its properties, making use of the server's events is like giving the server a "voice," allowing it to report back to your application. You might, for example, receive an event notification from the server when certain tasks are about to be or have been completed.

You enable your application to listen for these event notifications by using the WithEvents keyword. Use of the WithEvents keyword is restricted to variables defined in the declarations section of your module. Only object modules—that is, class and form modules—can contain variables declared using the WithEvents keyword. Once a module-level variable is declared as WithEvents, you can program against this event, enabling your application to respond to the changing state of the OLE automation server.

One word of warning when using the WithEvents keyword: if you are building a client-server system using a WithEvents object reference, you must ensure that the client machine gives permission for the server machine to create processes on it. Otherwise, even though the client can create instances of the ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.