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