Dynamically loading unmanaged OCX in C#

3

I have ocx created in VC++ If it is loaded statically it works fine but when I load it dynamically from assembly it gives exception .

    public Assembly assembly;

    public Form1()
    {
        InitializeComponent();            
       assembly = Assembly.LoadFile(Application.StartupPath + "\\abc.ocx");

    }

it gives following exception The module was expected to contain an assembly manifest.

(Exception from HRESULT: 0x80131018)

c#
ocx
asked on Stack Overflow May 3, 2012 by abdul • edited Apr 7, 2014 by GEOCHET

2 Answers

5

You'll have to perform a number of steps that are normally taken of automatically when you use the toolbox. First and foremost, you have to run the Aximp.exe utility to generate the .NET interop assemblies. Use the Visual Studio Command Prompt to run the tool. You'll get two assemblies, axinterop.foo.dll contains a wrapper class that's derived from AxHost and allows you to put the control on a form. And interop.foo.dll, the interop assembly that makes the COM interfaces implemented by the control callable from a .NET program.

Next you have to ensure these DLLs are present in the build directory. Best thing to do is to add them to your project and set their Copy to Output Directory to "Copy if newer".

Now you can use Assembly.Load("axinterop.foo.dll") in your code to dynamically load the interop assembly.

Next you have to create an instance of the control, use Assembly.CreateInstance() and pass the type name of the AxHost wrapper class. If you have no idea what its name might be, it isn't obvious, then use ildasm.exe to look at the axinterop.foo.dll assembly. Cast the returned object to AxHost.

Next you have to add the control to the form's Controls collection so it is visible and usable. You cannot call any interface methods until the control instance is created, that doesn't happen until you've added the control and the form's Load event has fired.

Next you have to use reflection or the dynamic keyword to obtain a reference to the interfaces implemented by the control, in case you need to set properties or call methods. That's difficult to get right, you'll want to write that code first with the control added from the toolbox so you don't have to guess too hard at the proper names.


This is obviously all quite painful and hard to get right. Improve the odds for a good outcome by adding a class library to your project that uses the OCX directly and exposes its important properties through an interface. And use Assembly.Load() on that one.

answered on Stack Overflow May 3, 2012 by Hans Passant • edited May 3, 2012 by Hans Passant
1

Assembly.LoadFile can only load .Net assemblies not native dll/exe/ocx files.

You can add a reference to the ocx file via Solution Explorer-->References and then create an instance of the ocx class.

answered on Stack Overflow May 3, 2012 by logicnp

User contributions licensed under CC BY-SA 3.0