Reputation: 31
I try to avoid using Type Libraries for COM automation with C#, but instead using the dynamic keyword to resolve types at runtime. This works fine, except when trying to define event handler.
I've tried to define it this way:
_COMObject.OnStop += new Action(OnStop);
The original COM object however defines its ownEventHandler type with no arguments and no return value. Thus of course Action is not the same type then and this results in a RuntimeBinderException stating that it can not convert the Action type to the ComObjectCustomEventHandler although they have the same signature.
I would need to have something like a dynamic delegate, however I haven't figured out how to define it.
Upvotes: 1
Views: 150
Reputation: 31
I figured it out how to do it with reflection. I've defined the following helper method:
private void AddEventHandler(string eventName, Delegate method)
{
EventInfo eInfo = _COMObject.GetType().GetEvent(eventName);
MethodInfo evHandler = method.GetMethodInfo();
Delegate del = Delegate.CreateDelegate(eInfo.EventHandlerType, this, evHandler);
eInfo.AddEventHandler(_COMobject, del);
}
Now I can call this method to add an event handler to it:
AddEventHandler("OnStop", new Action(OnStop));
Upvotes: 2