Connecting an OCX to a C# application is really easy. To test it, I created a new C# Windows forms app. Then I needed to connect the OCX.
- First, open the main form in design mode of this new project.
- Open the Toolbox.
- Right mouse on the Toolbox to get the popup menu.
- Select Choose Items...
- Go find your OCX and select it.
- It will now be placed in the Toolbox.
- Now, find it and drag and drop it to your form.
- At this point, it adds creates AxInterop.<ocxname>Lib.dll and adds it as a reference to your project and, of course, adds code to the MainForm.Designer.cs.
- You now have access to you OCX. You can call its methods and create events.
- If you don't want the OCX on the MainForm, you can create a new class to contain the logic and cut it out of MainForm.Designer.cs (Now that you have the generated interop dll).
- Stripped down, all you really need is this:
- ActXCtl = new AxAB2ACTXLib.AxAB2ActX();
- ActXCtl.CreateControl();
- To call a method of the OCX, it's as simple as: ActXCtl.SetAlarm()
- An example of creating an event handler:
_DAB2ActXEvents_AlarmSetEventHandler(OnAlarmSet);
ActXIface.Instance.ActXCtl.AlarmSet += AlarmSetEventHandler;
Example event handler:
private void OnAlarmSet(object sender, _DAB2ActXEvents_AlarmSetEvent e)
{
//The contents of "e" depends entirely on the OCX definition of the event.
//Simply type "e." to get at the data.
}
The key to this whole process is that it generates the interop dll and gives you the two lines of code you need to create the variable and control. Variable completion will fill in the rest for you in getting the alarms and methods working. In my example, I will be using ActXCtl and AxAB2ACTXLib to get at the methods and event data types, respectively.
You will also have to add this to the top of your cs file: using AxAB2ACTXLib;
I spent a few day looking for how to do this and thought it might be helpful to others. I read a lot of complicated ways to get this done. I couldn't get them to work, so I just gave this simple way a try and it worked! There's always legacy software to deal with.
Jim