简体   繁体   中英

Consume Event Generated by VB6 OCX in C#

I'm trying to access a VB6 OCX via C# using late binding.

I am able to Invoke the Methods using the Reflection / InvokeMember, however, I do not know how to consume the events generated by the OCX.

Im instantiating the OCX using the CreateInstance Method.

Code Snippet:

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" }); 

The above code works fine and it does Launch the Browser. If the user closes the Browser window that just opened, the OCX Triggers a "CloseWindow" event. How can I consume that event?

Judging by MSDN, the Type class seems to have a GetEvent method , which takes a string (being the event name).

This returns an EventInfo class which contains an AddEventHandler method.

My guess would be that calling GetEvent , and then calling AddEventHandler on the returned object would allow you to subscribe to the event, but I haven't tested it.

Something like this:

//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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM