1

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.

2
  • If it has no return value then it is impossible, it must return HRESULT to support late binding. Sounds pretty unlikely btw, programmers very rarely get this wrong. Use Oleview.exe, File + View Typelib command and show us the interface. Commented Sep 9, 2015 at 7:27
  • @HansPassant: Yes you are right it is defined as HRESULT OnStop(); Commented Sep 9, 2015 at 12:08

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.