Embedding an OCX in a .NET Form/Control and Calling its Methods

[update: for a better approach see ActiveX OCX and Windows.Forms Interop: Properties and Events]

Scenario: Embedding a COM (i.e. old vb6) OCX in a .net form and calling methods /
setting properties on it.
Problem: Drag-n-drop onto the form from the toolbox is garbage; dynamically
creating it works, but calling methods and setting properties doesn't seem to work.
Solution: be sure to get the order correct, and call
((ISupportInitialize)(control)).EndInit(); BEFORE you InvokeMember() with reflection

Example:
/*sample code not meant to compile. see also:
http://ask.metafilter.com/45181/How-to-create-an-instance-of-an-ActiveX-control-in-C-at-runtime
*/
Type type = null;
AxControl control = null;
try{
     type = Type.GetTypeFromProgID("MyCom.ProgId", true);
     control = new AxControl(type.GUID.ToString()); 
}catch (Exception ex){
     MessageBox.Show("Please ensure that " + progId + " is properly registered\n" + ex.ToString());
     return;
}
((ISupportInitialize)(control )).BeginInit();
//do stuff here like adding things to your win form, etc.

//control.GetOcx() == null !! InvokeMember() will fail

((ISupportInitialize)(control)).EndInit();
// !!!!!!!!!!!!
//NOW control.GetOcx() != null and you can call methods / properties!!
object[] args = new object[] { 1, 2 };
object r = type.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, 
          null, component.GetOcx(), args); 
//r will be the result of your "Add" method,as an example, in your embedded ocx

Categories

,
| Comments (0)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: Embedding an OCX in a .NET Form/Control and Calling its Methods.

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/73

Leave a comment