本文发表在 rolia.net 枫下论坛我希望通过 C# code 以 late binding方式访问COM组件, 需要hook C# event sink to the COM server event source。 (early binding没问题)。
我的实现方式如下:
// Obtain the COM object type by late binding, "Handler.Task" is the COM progID
string progID = "Handler.Task";
Type objectType = Type.GetTypeFromProgID(progID);
// Create Instance of COM object
object objHandler = Activator.CreateInstance(objectType);
// Get the event info, "OnStatusUpdate" is the method name inside the event source dispinterface in COm
EventInfo statusEvent = objectType.GetEvent("OnStatusUpdate");
// Create the the event sink
SampleEventSink statusSink = new SampleEventSink();
// "OnStatusUpdate" is the implementation method in the sink
MethodInfo invokeMehtod = statusSink.GetType().GetMethod("OnStatusUpdate");
Delegate eventSink = Delegate.CreateDelegate(statusEvent.EventHandlerType, invokeMehtod);
// Hook the sink to the source
statusEvent.AddEventHandler(objHandler, eventSink);
// Invoke method from the COM object
object hrTaskHandler = objectType.InvokeMember("Execute", BindingFlags.InvokeMethod, null, objHandler, new object[] { taskName, taskArg });
我的问题是:
1。 我的实现方式对否?
2。 按以上代码, objectType.GetEvent("OnStatusUpdate")返回null. 我尝试用GetEvents返回所有Event, 也是null. 我估计该Event包含在nested的type中, 尝试GetNestedTypes, GetInterfaces等方法先返回次级Type, 都是null。
请大家帮忙看看, 谢谢。更多精彩文章及讨论,请光临枫下论坛 rolia.net
我的实现方式如下:
// Obtain the COM object type by late binding, "Handler.Task" is the COM progID
string progID = "Handler.Task";
Type objectType = Type.GetTypeFromProgID(progID);
// Create Instance of COM object
object objHandler = Activator.CreateInstance(objectType);
// Get the event info, "OnStatusUpdate" is the method name inside the event source dispinterface in COm
EventInfo statusEvent = objectType.GetEvent("OnStatusUpdate");
// Create the the event sink
SampleEventSink statusSink = new SampleEventSink();
// "OnStatusUpdate" is the implementation method in the sink
MethodInfo invokeMehtod = statusSink.GetType().GetMethod("OnStatusUpdate");
Delegate eventSink = Delegate.CreateDelegate(statusEvent.EventHandlerType, invokeMehtod);
// Hook the sink to the source
statusEvent.AddEventHandler(objHandler, eventSink);
// Invoke method from the COM object
object hrTaskHandler = objectType.InvokeMember("Execute", BindingFlags.InvokeMethod, null, objHandler, new object[] { taskName, taskArg });
我的问题是:
1。 我的实现方式对否?
2。 按以上代码, objectType.GetEvent("OnStatusUpdate")返回null. 我尝试用GetEvents返回所有Event, 也是null. 我估计该Event包含在nested的type中, 尝试GetNestedTypes, GetInterfaces等方法先返回次级Type, 都是null。
请大家帮忙看看, 谢谢。更多精彩文章及讨论,请光临枫下论坛 rolia.net