C# - Hook into existing COM object

.net, c#, com, hook, interop

Solution

You can use ActiveX Import AxImp to import the OCX, create a wrapper class and then call that. The program is described here: http://msdn.microsoft.com/en-us/library/8ccdh774(VS.80).aspx Basically, what you need to do is execute the following on the commandprompt:

c:/>AxImp MyControl.ocx

result is a MyControl.dll and an AxMyControl.dll. The first you can use as a normal .NET DLL in your projects (i.e., without a graphical user interface), the second can be used to be drawn on a form as you normally would with any other control like a `TextBox` or a `Label`.

To use it, go to Visual Studio, rightclick your project and select Add Reference. Browse to the newly created DLL and add it. That's all.

Problem

Say we have an existing process (or application) that calls a COM object from an ocx file such as "MyCOMLibrary.ocx". Is there a way to write a C# library to exactly replicate the ocx file? So that the original application can call your C# code rather than the original COM object? You would, of course, have to use identical CLSID and ProgIDs as the original ocx. And assuming there is no signing involved, such as a SNK in the .Net world. Also, are there any tools that exist to automate this? Something that takes in an ocx and spits out a C# file with methods to implement. EDIT: I want to add that the original application is VB6, and does not use .Net at all. They are most likely loading the ocx as a VB6 app would (ProgId or Guid). Does this cause any issues? We also have no problem with completely rewriting the ocx--we will most likely just return success error codes for all methods and only use methods/events required by our situation. EDIT: You would think this would not be too difficult to accomplish. Can we make a VB6 ocx file that could replace the old ocx, and just pass all calls to a .Net assembly? EDIT: I tried using the following open source library: EasyHook But it seems like this question should still be viable. VB6 seems to load COM objects in a way that prevents hooking. I don't see a way to hook instance methods on a class/interface or a class's constructor with EasyHook.

Original source