【问题标题】:Consume Event Generated by VB6 OCX in C#C# VB6 OCX 生成的消费事件
【发布时间】:2014-06-23 06:49:47
【问题描述】:

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

我可以使用 Reflection / 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”事件。如何使用该事件?

【问题讨论】:

    标签: c# com activex com-interop ocx


    【解决方案1】:

    根据 MSDN 判断,the Type class seems to have a GetEvent method,它接受一个字符串(作为事件名称)。

    这将返回一个包含AddEventHandler 方法的EventInfo 类。

    我的猜测是调用 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);
    }
    

    【讨论】:

    • var eventInfo = t.GetEvent("CloseWindow");此代码始终返回空值
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多