我正在尝试使用后期绑定(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/