首页 > 解决方案 > C# 使用 System.Reflection 订阅 COM 对象的事件

问题描述

我必须遵循没有 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();
          }
    }

}

我有兴趣获得 OperationComplete 事件的结果。如何用 System.Reflection 实现???

直到现在我有这个代码:

//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

这可能吗?

谢谢!

UPDATE1:我得到一个建议,我应该使用ComEventsHelper类,但我不知道如何将它插入到我的代码中。

标签: c#comruntimesystem.reflection

解决方案


推荐阅读