如何知道是否有人订阅了我将要触发的特定事件?

How to know if anybody has subscribed to a particular event I'm going to fire?

本文关键字:事件 是否 何知道      更新时间:2023-10-16

我的 ActiveX/ATL 库中有 2 个事件

dispinterface _IMyEvents
{
    properties:
    methods:
    [id(1), helpstring("method OnReceiveData")] HRESULT OnReceiveData([in] long BytesReceived, [in, out] VARIANT_BOOL * Proceed);
    [id(2), helpstring("method OnReceiveDataEx")] HRESULT OnReceiveDataEx([in] long BytesReceived, [in] BSTR DataChunk, [in, out] VARIANT_BOOL * Proceed);
 };

它们以标准 ATL 的方式调用:

 template <class T>
 class CProxy_IMyEvents : public IConnectionPointImpl<T, &DIID__IMyEvents, CComDynamicUnkArray>
 {
    //Warning this class may be recreated by the wizard.
 public:
    HRESULT Fire_OnReceiveData(LONG BytesReceived, VARIANT_BOOL * Proceed)
    {
        CComVariant varResult;
        T* pT = static_cast<T*>(this);
        int nConnectionIndex;
        CComVariant* pvars = new CComVariant[2];
        int nConnections = m_vec.GetSize();
        for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++)
        {
            pT->Lock();
            CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex);
            pT->Unlock();
            IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p);
            if (pDispatch != NULL)
            {
                VariantClear(&varResult);
                pvars[1] = BytesReceived;
                pvars[0].vt = VT_BYREF|VT_BOOL;
                pvars[0].pboolVal = Proceed;
                DISPPARAMS disp = { pvars, NULL, 2, 0 };
                pDispatch->Invoke(0x1, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL);
            }
        }
        delete[] pvars;
        return varResult.scode;
    }

我需要知道应用程序是否特别订阅了OnReceiveDataEx事件(该事件具有需要计算的额外参数DataChunk)。如果应用程序只侦听 OnReceiveData,我不需要构建 DataChunk 字符串,因为没有人会得到它,并且可以优化性能。

但是,ATL 只允许我知道是否有人订阅了任何事件,但不允许我特别订阅哪些事件(所以我只能确定侦听我的事件的对象(接收器)的数量,而不能确定正在侦听的特定事件的数量和名称)。有什么办法可以克服这个问题吗?

例如,在 .net 中,您可以独立于其他事件检查事件的订阅者。

如果需要进行此区分,ATL 或 no,则需要两个接口。一个用于OnReceiveData,一个用于OnReceiveDataEx。给定的事件接收器必须实现事件接口的所有方法,即使它只关心一个方法。