Search code examples
c#comocx

Calling OCX(COM) method using C#


I am using an OCX library from C#. I have added COM reference from Visual Studio. When I try to create an object in this class I am getting,

var ocxCls = new MyOCXClass();

CS1729  'MyOCXClass' does not contain a constructor that takes 0 arguments

If I use reflection to see the parameters and constructor count,

        Type tt = typeof(MyOCXClass);
        var  flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var cs = tt.GetConstructors(flags)[0].GetParameters().Count();

The constructor's count is 1 and parameters 0? What's happening?

Update: When I opened OCX inside OLEView I got,

enter image description here


Solution

  • Instead of using the Console application, I have used a WinForm application. Now Visual Studio generates a class that I am able to instantiate.

    In Console the class generated was,

    [ClassInterfaceAttribute(0)]
    [ComSourceInterfaces("OCX.__OCX")]
    [Guid("SomeGuid")]
    [TypeLibType(32)]
    public class OCXClass : _OCX, OCX, __OCX_Event
    {
        [DispId(1610809349)]
        public virtual void OCXMethod1(ref short milliseconds);
        [DispId(1610809350)]
        public virtual bool OCXMethod2();
    }
    

    While in WinForms it shows,

    [Clsid("{SomeGuid}")]
    [DesignTimeVisible(true)]
    public class OCXClass : OCXClassHost
    {
        public OCXClass();
        public virtual void OCXMethod1(ref short milliseconds);
        public virtual bool OCXMethod2();
    }
    

    When I use JustDeCompile I also see,

    [ClassInterfaceAttribute(0)]
    [ComSourceInterfaces("OCX.__OCX")]
    [Guid("SomeGuid")]
    [TypeLibType(32)]
    public class OCXClass : _OCX, OCX, __OCX_Event
    {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
        internal extern OCXClass();
    

    Note the internal extern constructor which I think stopping me to create an object.