COM Class in C# << Back



Almost a year ago, Michael Mullan asked on the DAW support forum on how to create COM Class in C#. Michael Salzlechner (AKA StarZen) replied with a helpful article of his own here. I decided to follow the steps from that article to create my very first COM Class using C#. All was well. A year later, Michael Mullan now wants to know how to add Events into his COM Class in C#. As this is a slow Sunday, I figure I would give it a go even without the promise of any Bushmills.

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace Bushmills
{

    [ComVisible(true)]
    [Guid("e68a61b0-a1ed-40b3-b544-5ab16479c800")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IBushmillsEvents
    {
        [DispId(1)]
        void OnFinishDrinking();
    }

    [ComVisible(true)]
    [Guid("d15c7619-e9f0-49b9-a28d-463f29f63d8c")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IBushmills
    {
        [DispId(1)]
        string WhatAreYouHaving();

    }

    [ComVisible(true)]
    [Guid("1c294eda-11d7-49fa-9794-0d4e53c288d9")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(IBushmillsEvents))]
    [ProgId("Bushmills")]
    public class Bushmills: IBushmills
    {

        public delegate void OnFinishDrinkingDelegate();
        private event OnFinishDrinkingDelegate OnFinishDrinking;

        private void DrinkingThread()
        {
            Thread.Sleep(1000);
            OnFinishDrinking();
        }
        public string WhatAreYouHaving()
        {
            Thread timerThread = new Thread(DrinkingThread);
            timerThread.Start();
            return "Black Bush";
        }
    }
}

On the VDF side

Use FlexCom20.pkg

Class cComIBushmills is a Mixin
    Function ComWhatAreYouHaving Returns String
        Handle hDispatchDriver
        String retVal
        Get phDispatchDriver to hDispatchDriver
        Get InvokeComMethod of hDispatchDriver 1 OLE_VT_BSTR to retVal
        Function_Return retVal
    End_Function
End_Class

Class cComIBushmillsEvents is a Mixin
    Procedure OnComFinishDrinking
    End_Procedure
    Procedure RegisterComEvents
        Send RegisterComEvent 1 msg_OnComFinishDrinking
    End_Procedure
End_Class

Class cComBushmills is a cComAutomationObject
    Import_Class_Protocol cComIBushmills
    Import_Class_Protocol cComIBushmillsEvents

    Procedure Construct_Object
        Forward Send Construct_Object
        Set psProgID to "{1C294EDA-11D7-49FA-9794-0D4E53C288D9}"
        Set psEventId to "{E68A61B0-A1ED-40B3-B544-5AB16479C800}"
        Set peAutoCreate to acNoAutoCreate
    End_Procedure
End_Class

Free Web Hosting