Search code examples
c++asynchronoustimercomvb6

How can I write a C++ COM object with asynchronous event firing (like VB6's Timer object)?


I'm writing a C++ COM object for directory change notifications via ReadDirectoryChangesW. A thread in my object will wait for changes, then notify the VB6 client.

I know how to trigger events from the main thread of my program, similar to callback functions, but I don't want to force the user to poll my object for changes every small interval.

As far as I'm aware, what I want could be done by sending window messages, but this needs form subclassing on the VB6 side, which is quite complicated.

So I'm looking for a way to write an object like VB6's Timer which can fire an event in VB6 even when VB6 isn't currently calling into a method of Timer. Is this possible?


Solution

  • COM events.

    The topic is rather laborious, it implies defining a 'sink' interface that the event consumer (VB) is passing to the event source, and then raising events by calling methods on the 'sunken' interface. See Architecture of Connectable Objects. You must implement IConnectionPointContainer. The good news is that IDEs are fully aware of this model and will expose your events in the VB designer. From the VB side will be as simple as a double-click on the COM object 'events' properties panel.

    As for the 'async' part, this falls in the 'threading' model of your component and the VB host app. In Apartment threads (the default) you will have to raise the events in the main Apartment thread, and you may have to marshal the interface between threads. See What are the rules for CoMarshalInterface and CoUnmarshalInterface?.

    The details about asynchronous COM event firing from C++ server to VB6 client can be found in this article.