How can I make an ActiveX control written with C# raise events in JavaScript when clicked?

ActiveX events are handled via COM, so you need to delve in there a bit unfortunately.

The thing to remember with COM is that everything is handled via interfaces, so you normally need to create two interfaces, one for any properties and one for your events.

The key for events is marking your class with the ComSourceInterfaces attribute, which is described by MSDN as “Identifies a list of interfaces that are exposed as COM event sources for the attributed class.”

This simple class structure should work for you (it has for me in the past).

namespace MyActiveX
{
    [Guid("Your-GUID") ,InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IActiveXEvents
    {
        [DispId(1)]
        void OnMouseClick(int index);
    }

    [Guid("Another-GUID"),InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IActiveX
    {       
        //[DispId(1)]
        // Any properties you want here like this
        // string aProperty { get; set; }        
    }

    [ComVisible(true)]
    [Guid("Yet-Another-GUID"), ClassInterface(ClassInterfaceType.None)]
    [ProgId("MyActiveX")]
    [ComSourceInterfaces(typeof(IActiveXEvents))]
    public partial class MyActiveX : UserControl, IActiveX
    {
        public delegate void OnMouseClickHandler(int index);

        public event OnMouseClickHandler OnMouseClick;

        // Dummy Method to use when firing the event
        private void MyActiveX_nMouseClick(int index)
        {

        }

        public MyActiveX()
        {
            InitializeComponent();

            // Bind event
            this.OnMouseClick = new OnMouseClickHandler(this.MyActiveX_MouseClick)
        }

        public void FireTheEvent()
        {
            int index = -1;
            this.OnMouseClick(index);
        }       
    }
}

If you don’t need any properties you can just exclude the IActiveX interface. Also if you are going to use the Click event, you will need to mark it as new to pass it to COM.

Leave a Comment