问题
I have an Interface in c# in which i have declared event for example:
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("3839C631-AEDE-4535-9A28-15F4BFCA0C5A")]
public Interface Isample
{
event OnAdd(Isample sample);
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("E81B32A2-B98C-48C0-A235-17771EE001D6")]
[ComVisible(true)]
public class Sample:Isample
{
//'''''''''''''''''''''
}
I want to fire this event in c# and listen it into javascript through firebreath.
Thanks in advance.
回答1:
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.
回答2:
[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_")
来源:https://stackoverflow.com/questions/20488379/how-to-fire-c-sharp-com-events-in-c