How to fire c# COM events in c++?

[亡魂溺海] 提交于 2019-12-08 19:49:50

COM events are very different from C# events. They are much more generic, the event listener must implement an interface and tell the event source about it through IConnectionPoint. The event source then "raises" an event simply by calling the interface method. You thus need to:

  • Write an interface that declares methods, not events. So simply void Add(ISample sample) in your case.
  • Don't inherit the interface in your class declaration, it is the job of the event listener to implement it.
  • Declare a public event in your C# class whose name exactly matches the method in the interface
  • Allow the CLR to implement IConnectionPointContainer for you by telling it about the interfaces, use the [ComSourcesInterfaces] attribute.

This MSDN article shows an example.

[ComVisible(true)] 
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 
public interface IComScriptEngineEvents
{
  /// <summary>
  /// 
  /// </summary>
  /// <param name="message"></param>
  [DispId((int)IComScriptEngineEventsDispatchIDs.CompileError)]
  void CompileError(string message);
}


[ClassInterface(ClassInterfaceType.None)]
[ProgId("ScriptEngineComWrapper.ComScriptEngine")]
[ComVisible(true)]
[ComSourceInterfaces(typeof(IComScriptEngineEvents))]
public class ComScriptEngine : IComScriptEngine
{
    [ComVisible(false)]
    public delegate void CompileErrorDelegate(string message); 

    public event CompileErrorDelegate CompileError;
}

call then inside a method in comscriptengine //this.CompileError("from event!");

I do not know why I have this delegate, but for some reason I had to use it. The source was written a few years ago.

VB-Script Testcode

Sub event_CompileError(strMessage)
  MsgBox strMessage
End Sub


Set objScriptEngine = WScript.CreateObject("ScriptEngineComWrapper.ComScriptEngine", "event_")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!