ActiveX control without a form

Viewed 16921

We are required to use a 3rd party ActiveX control.

The only issue is, the layer in our software is a business layer and has no access to a window or form. It also runs on separate threads (and should work from any thread) that are not STA.

Rather than breaking our separation of UI from business logic, we used this workaround to make it work:

Thread thread = new Thread((ThreadStart)
delegate
{
_myActiveX = new MyActiveXType();
_myActiveX.CreateControl();

//more initialize work

Application.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();

Then anytime we need to reference the control, we call _myActiveX.BeginInvoke() or Invoke().

On disposing of this class (exiting our app), we dispose the control and abort the thread.

My question is, are there any problems with this? Is there a better way to handle this?

Is there a better built in way to work with an ActiveX control from within an unknown multi-threaded environment? We are trying to write our class in a way that wraps the control but will work from any thread.

UPDATE: As an answer suggested, we really would rather use the standard COM object and not use a control at all. Our issue with that was we would get the error "(Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)" upon the first method or property we call on the COM object. This is a pretty generic error that we don't get when using the ActiveX, any ideas?

UPDATE: Our ocx is "CX25.ocx", using tlbimp.exe we get CX25Lib.dll. Using aximp.exe, we get AxCX25Lib.dll and CX25Lib.dll. CX25Lib.dll does not work in either case. AxCX25Lib.dll works.

5 Answers

The CreateControl() method is from AxHost and requires System.Windows.Forms as a dependency. If you want to use ActiveX without UI you can directly create COM object of ocx using native call.

   [DllImport("ole32.dll", PreserveSig = false)]
    [return: MarshalAs(UnmanagedType.Interface)]
    public static extern object CoCreateInstance([In] ref Guid clsid,[MarshalAs(UnmanagedType.Interface)] object punkOuter,int context, [In] ref Guid iid);


public object createComObject(){ 
    Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");

    var gid = "{6bf52a52-394a-11d3-b153-00c04f79faa6}"; //your ocx guid
    var clsid = new Guid(gid);

    object yourOCX = CoCreateInstance(ref clsid, (object)null, 1, ref IID_IUnknown);
  return yourOCX ;
}

You can later cast the COM object to required interfaces

IOleObject iole = yourOCX as IOleObject;

IWMPCore iwmp =  yourOCX as IWMPCore;

I have created Windows Media Player ActiveX without UI or AxHost in C# over this link. It might help someone trying to run ActiveX without UI.

Related