in Development

Building ActiveX with .NET

These days I’ve participated in the contest Gadgetizate which goal was to build a Sidebar Gadget.

As you know the gadgets should be coded using Html and script and you have also access to a wide variety of namespaces, but there are some cases in which you want more. There are some tricks to expand his functionality like embedding WPF applications or using ActiveX.

With .NET we can build easily ActiveX and/or COM components. Next you can see how to do it.

The first thing you need to do when you create your project is go to the "Build" properties tab and mark the option "Register for COM interop". This indicates that your application will expose a COM object and Visual Studio will register automatically for you. You can do that later on by using the tool Regasm.exe.

There are some requirements for the classes to be able to use .NET objects as COM:

  • The class, properties, methods and events must be public
  • The class must implement the interface with the members that will be exposed, methods not defined in the interfaces will not be exposed as COM.

With the next code you will be ready to create your first ActiveX component.

   1: namespace Blog
   2: {
   3:     [Guid("E7CB6236-5436-4a5a-A22C-DCB5EEA453E1")]
   4:     [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
   5:     interface IMyActiveX
   6:     {
   7:         [DispId(1)]
   8:         string HelloWorld();
   9:     }
  11:     [Guid("3D7DADC0-CFA9-4248-89BF-36A8914AE155")]
  12:     [ClassInterface(ClassInterfaceType.None)]
  13:     [ProgId("Blog.MyActiveX")]
  14:     public class MyActiveX : IMyActiveX
  15:     {
  17:         public string HelloWorld()
  18:         {
  19:             return "Hello world";
  20:         }
  21:     }
  22: }

Notice that the interface and the class are marked with the GuidAttribute, these are the Guid’s that will be used to identify your classes, this is an optional attribute since the tool TlbImp.exe creates for you if the attribute is not set, but assigning manually gives you more control over the ActiveX, since you can then use it to locate, load …

If you pay attention to the interface you will see that the method has also an attribute, the DispId, this as you can imagine, assigns a dispatch id to the method HelloWorld, in order it can be accessed through the IDispatch interface.

The last thing to do is to sign your assembly and that’s all, you are now ready to use it from your web pages or gadgets using the next JavaScript code.

   1: var activeX = return new ActiveXObject("Blog.MyActiveX");
   2: var text = activeX.HelloWorld();