2

I have to following code that is working without System.Reflection:

Using COMlib;

namespace test
{
    class Program
    {
          private static void kxc_operationComplete(object result)
          {

          }

          static void Main(string[] args)
          {
               COMclass kxc = new COMclass();
               kxc.Init();
               kxc.OperationComplete += kxc_operationComplete;
               kxc.Operate();
          }
    }

}

I'm interested to obtain the result of the OperationComplete event. How can be achieved with System.Reflection???

Until now I have this code:

//getting active x type
var COMtype = Type.GetTypeFromCLSID(Guid.Parse(CLSID.objcode), true);
//create object
object COMobj = Activator.CreateInstance(COMtype);
//call init method
COMtype.InvokeMember(“Init”, BindingFlags.InvokeMethod, null, COMobj, null);


//query for event
EventInfo ei = COMtype.GetEvent(“OperationComplete”);  //the eventinfo is null
//bind to my class method
MethodInfo method = Type.GetType("test.Program").GetMethod("kxc_operationComplete");
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, kxc, method);
//but is not working

Is this possible?

Thank you!

UPDATE1: I got a suggestion that I shoud use ComEventsHelper class, but I don't know how can it be inserted into my code.

Adrian Stanculescu
  • 1,040
  • 2
  • 13
  • 21
  • What does Type.GetEvents return? – Markus Dresch Jul 04 '18 at 12:29
  • 1
    Type.GetEvents returns an empty array, also Tyep.GetMethods returns a list of methods that doesn't contain Init and Operate methods, but I'm able to invoke them. I think is related to the late binding of a COM object. – Adrian Stanculescu Jul 04 '18 at 12:33
  • How about changing "OperationComplete" to "operationComplete"(case sensitive)? – kunif Jul 04 '18 at 13:37
  • No luck, because OperationComplete is the event name. – Adrian Stanculescu Jul 04 '18 at 13:39
  • Seems to be a @jon-skeet question – Adrian Stanculescu Jul 04 '18 at 13:58
  • 1
    These [AddEventHandler using reflection](https://stackoverflow.com/questions/1121441/addeventhandler-using-reflection), [c# Adding a listener to Event with only the method name (text)](https://stackoverflow.com/questions/49290793/c-sharp-adding-a-listener-to-event-with-only-the-method-name-text) may be helpful. From that, how about trying COMobj.GetType().GetEvent() instead of COMtype.GetEvent()? – kunif Jul 04 '18 at 15:23
  • 1
    I've tried first link. Actually my code adapts the link code. COMobj.GetType().GetEvent() is equal with COMtype.GetEvent(). I've tried both ways. Thanks. – Adrian Stanculescu Jul 04 '18 at 15:35

0 Answers0