c# - 在 C# 中使用 VB6 OCX 生成的事件

标签 c# com activex com-interop ocx

我正在尝试使用后期绑定(bind)通过 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”事件。我如何使用该事件?

最佳答案

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

这会返回一个 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);
}

关于c# - 在 C# 中使用 VB6 OCX 生成的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498388/

相关文章:

c# - 如何设置 asp :HyperLink href to "mailto:abc@hotmail.com" in .net c#

c# - TcpClient BeginRead/Send 线程安全吗?

windows - 使用 Windows Compact 2013 Virtual PC 打开 COM 端口

c# - SetApartmentState 和 [STAThread]

c - 处理 IE 窗口内的 ActiveX 组件

c# - 在 IE 中托管时在 .NET 中创建的 ActiveX 控件不接收键盘事件

javascript - ActiveXObject 创建错误 "Automation server can' t 创建对象”

c# - 带有文字字符串的数组

c# - 3 类员工排类 24/7 模式

windows - DCOM 中的模拟是如何工作的?