我正在尝试使用后期绑定通过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”事件。我该如何消费该事件?
答案 0 :(得分:0)
以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);
}