As a C# developer, you can still use and respond to events published by COM clients. There are two ways to do this: use the RAW method or use event abstraction. The latter method is much easier.
When you run tlbimp.exe or another tool that performs the same function, the following four items are generated in the Interop DLL:
The SourceInterfaceName_Event interface, which is similar to the source interface, except it is .NET version of the interface describing the events.
SourceInterfaceName_MethodNameEventHandler, which acts as the delegate when subscribing to the event.
SourceInterfaceName_EventProvider is a private class that implements the interface created in SourceInterfaceName_Event. This handles the connection point requirements.
SourceInterfaceName_SinkHelper is a private class that implements the source interface and is used in the call to IConnectionPoint.Advise.
By using the event abstraction method to subscribe to events, you have the added flexibility of being able to subscribe to a single event, rather than to all of the events described in the event interface, which was the normal practice when using IConnectionPoints.
The following examples demonstrate using event abstraction to subscribe to events in COM objects and publishing .NET objects to COM with events.
using System; using SHDocVw; namespace Client.Chapter_10___COM_and_.NET_Interoperability { class BrowserListener { private InternetExplorer ie; public BrowserListener() { ie = new InternetExplorerClass(); ie.DocumentComplete += DWebBrowserEvents2_DocumentCompleteEventHandler(DocComp); ie.TitleChange += new DWebBrowserEvents2_TitleChangeEventHandler(TitleMod); ie.Visible = true; ie.GoHome(); } public void DocComp(object pDisp, ref object URL) { Console.WriteLine("Document Complete: " + URL); } public void TitleMod(string Text) { Console.WriteLine("Title Change: " + Text); } [STAThread] static void Main(string[] args) { BrowserListener listener = new BrowserListener(); Console.WriteLine("*** Press Enter to quit ***"); Console.Read(); } } }
using System; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; namespace Client.Chapter_10___COM_and_.NET_Interoperability { public delegate void CallbackDelegateHandler(bool myBool); [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ITest { [DispId(1)] void Callback(bool test); } [ComSourceInterfaces(typeof(ITest))] [ClassInterface(ClassInterfaceType.AutoDual)] public class Repro { public Repro() { } public event CallbackDelegateHandler Callback; public void Test() { Debug.WriteLine("Testing"); } public void DoWork() { Thread MyThread = new Thread(new ThreadStart(ThreadProc)); MyThread.Start(); } public void ThreadProc() { Callback(true); } } }