This is an old revision of the document!


Creating COM Library

Source: http://stackoverflow.com/questions/3360160/how-do-i-create-an-activex-com-in-c

  • Start VS2010 as administrator.
  • Open a Class Library project (Eg: MyLib).
  • Interface:
    • Add to the file:
      using System.Runtime.InteropServices;
    • Add a new interface to the project:
      public interface IMyLauncher
      {
         void launch();
      }
    • Add the attributes InterfaceType, Guid to the interface. Generate a Guid using Tools > Generate GUID.
      [InterfaceType(ComInterfaceType.InterfaceIsDual)]
      [Guid("F207154F-C7E9-42B7-92BA-D6C4DA4D0A55")]
  • Class:
    • Add a class that implement the interface.
    • Add the attributes ClassInterface, Guid, ProgId to the interface. Generate a Guid using Tools > Generate GUID.
      [InterfaceType(ComInterfaceType.InterfaceIsDual)]
      [Guid("0BE40A98-FCAC-432D-B0B6-999B42A28E48")]
      [ProgId("MyLib.MyLauncher")]
    • ProgId convention is {namespace}.{class}
  • Activate COM and register it:
    • In Project Properties (Alt-Tab) > Application > Assembly Information, check “Make Assembly COM-Visible”. Alternatively, In the folder MyLib > Properties > AssemblyInfo, set ComVisible to true.
    • In Project Properties (Alt-Tab) > Build > Output, and check “Register for COM interop”.
    • Build the project. This will register the COM object.
    • Alternatively, manually register COM object:
      C:\>"%Windir%\Microsoft.NET\Framework\v4.0.30319\regasm.exe" /codebase MyLib.dll

Now the COM object is available to be called by its ProgID.

Example class for COM:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.Runtime.InteropServices;
 
namespace MyLib
{
 
    [InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")]
    public interface IMyLauncher
    {
        void launch();
    }
 
    [ClassInterface(ClassInterfaceType.None), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYY"), ProgId("MyLib.MyLauncher")]
    public class MyLauncher: IMyLauncher
    {
        private string path = null;
 
        public void launch()
        {
            Console.WriteLine("Hello, World, from a COM object");
 
        }
 
    }
}

Example how to call COM object using VB script:

set obj = createObject("PSMyLib.PSMyLauncher") obj.launch()

Output:

Hello, World, from a COM object