在C#中消费由VB6 OCX生成的事件

3

我正在尝试使用C#通过晚期绑定访问VB6 OCX。

我能够使用反射/InvokeMember调用方法,但是我不知道如何消耗OCX生成的事件。

我正在使用CreateInstance方法实例化OCX。

代码片段:

Type t = Type.GetTypeFromProgID("MyOCX"); 
object test = Activator.CreateInstance(t); 
t.InvokeMember("LaunchBrowserWindow", System.Reflection.BindingFlags.InvokeMethod, null, test, new object[] { "cnn", "www.cnn.com" }); 

以上代码运行良好,可以启动浏览器。如果用户关闭了刚打开的浏览器窗口,OCX会触发“CloseWindow”事件。我该如何消费这个事件?

1个回答

0
根据MSDN,Type类似乎有一个GetEvent方法,它接受一个字符串(是事件名称)。
这将返回一个EventInfo类,其中包含一个AddEventHandler方法。
我猜测调用GetEvent,然后在返回的对象上调用AddEventHandler将允许您订阅事件,但我还没有测试过。
类似这样的东西:
//This is the method you want to run when the event fires
private static void WhatIWantToDo()
{
    //do stuff
}

//here is a delegate with the same signature as your method
private delegate void MyDelegate();

private static void Main()
{
    Type t = Type.GetTypeFromProgID("MyOCX"); 
    object test = Activator.CreateInstance(t); 
    t.InvokeMember("LaunchBrowserWindow", System.Reflection.BindingFlags.InvokeMethod, null, test, new object[] { "cnn", "www.cnn.com" });

    //Get the event info object from the type
    var eventInfo = t.GetEvent("CloseWindow");

    //Create an instance of your delegate
    var myDelegate = new MyDelegate(WhatIWantToDo);

    //Pass the object itself, plus the delegate to the AddEventHandler method. In theory, this method should now run when the event is fired
    eventInfo.AddEventHandler(test, myDelegate);
}

1
var eventInfo = t.GetEvent("CloseWindow"); 这段代码总是返回 null 值。 - Aneesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接