3
votes

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?

1

1 Answers

0
votes

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