In Chapter 11, you learned about the .NET event model. Recall that this architecture is based on delegating the flow of logic from one part of the application to another. The entity in charge of forwarding a request is a type deriving from System.MulticastDelegate, which we create indirectly in VB 2008 using the Delegate keyword.
When the tlbimp.exe utility encounters event definitions in the COM server's type library, it responds by creating a number of managed types that wrap the low-level COM connection point architecture. Using these types, you can pretend to add a member to a System.MulticastDelegate's internal list of methods. Under the hood, of course, the proxy is mapping the incoming COM event to their managed equivalents. Table 19-3 briefly describes these types.
Table 19-3. COM Event Helper Types
Generated Type (Based on the
_CarEvents [source] Interface) Meaning in Life
_CoCar_Event This is a managed interface that defines the add and remove members used to add (or remove) a method to (or from) the System.MulticastDelegate's linked list.
_CoCar_BlewUpEventHandler This is the managed delegate (which derives from
_CoCar_SinkHelper This generated class is used internally to map COM events to
As you would hope, the VB 2008 language does not require you to make direct use of these types. Rather, you are able to handle the incoming COM events in the same way you handle events based on the .NET delegation architecture. Simply declare the COM object WithEvents, and use the Handles keyword to map the event to a given method (or make use of the AddHandler/RemoveHandler statements).
Public WithEvents myCar As New CoCar()
Private Sub myCar_BlewUp() Handles myCar.BlewUp
Console.WriteLine("***** Ek! Car is doomed...! *****") End Sub End Module
Source Code The VbNetCarClient project is included under the Chapter 19 subdirectory.
That wraps up our investigation of how a .NET application can communicate with a legacy COM application. Now be aware that the techniques you have just learned would work for any COM server at all. This is important to remember, given that many COM servers might never be rewritten as native .NET applications. For example, the object models of Microsoft Outlook and Microsoft Office products are currently exposed only through a COM interop assembly. Thus, if you needed to build a .NET program that interacted with these products, the interoperability layer is (currently) mandatory.
Note Be aware that many COM component vendors (including Microsoft) have already created "primary interop assemblies" for commonly used COM applications (such as Office and Outlook). These primary interop assemblies have been optimized to ensure the best performance and will typically be listed within the COM tab of the Visual Studio 2008 Add Reference dialog box.
Was this article helpful?