winformsautomationactivexironpython

ActiveX control in ironpython windows form


I'm having difficulties with a set of activeX controls used for automation of lab instruments. I've got them all to work in VB, in forms applications - as they won't work in console applications. My company is working mainly with python and there would thus be a great advantage in writting our drivers in python, mainly for lims integration.

As such, I have tried to embed my activeX controls within ironpython windows forms. I've tried two different ways of introducing my controls in the forms:

1) with clr referencing the Ax dll after using AxImp on the original ocx. Then I add my instance of the control as a form control and try to run it from there. It throws System.Windows.Forms.AxHost+InvalidActiveXStateException.

import clr
clr.AddReferenceToFileAndPath(r"C:\dlls\AxVCode3Lib.dll")
clr.AddReferenceByPartialName("System.Windows.Forms")

import System.Windows.Forms as Forms
import AxVCode3Lib

class activeXform(Forms.Form):
    def __init__(self):
        a = AxVCode3Lib.AxVCode3()
        self.Controls.Add(a)
        for i in self.Controls:
            r = i.Initialize("serial")
            print r

form = activeXform()
raw_input(">exit")

2) Using SystemReflection and the ProgID, which throws a generic "Exception has been thrown by the target of an invocation". The following code was introduced in a basic ironpython windows form, however I was not able to add those objects as form controls.

import System.Type
import System.Reflection
import System.Array

oType = System.Type.GetTypeFromProgID("VCODE3.VCode3Ctrl.1")
o = System.Activator.CreateInstance(oType)
args = System.Array[str](['serial'])

try:
    r = oType.InvokeMember("Initialize", System.Reflection.BindingFlags.InvokeMethod, None, o, args)
    print r
except Exception as e:
    print e

Now I suspect both those examples fail due to some properties missing in my forms. However I can't figure out what it is, in particular in case 1 when the instance is actually added as a control, it seems I am very close.


Solution

  • You cannot use the methods of the ActiveX control until its native handle is created. In other words, not until after you call the form's Show() method.

    Make sure you get the basic outline of a Winforms application correct, peek in the Program.cs source code file of a sample C# Winforms app. The Application.Run() call is essential. Use the form's Load event (or override OnLoad) as the first event where you can actually start using the control.