VC++调用COM(含连接点事件)过程

时间:2022-02-23 19:46:51

VC++调用COM(含连接点事件)过程:已COM组件GstRealDb为例,内含接口方法IRealDb和事件_IRealDbEvents,VC++调用过程如下:1、先建立连COM事件的继承类Sink,类继承自事件接口(_IRealDbEvents),新定义的类必须包含_IRealDbEvents的定义文件,应在新工程中包含(GstRealDb.h和GstRealDb.tlb)文件,例如:#include "../../GstRealDb/GstRealDb.h"class CRealDbEventsSink : public IDispEventImpl<1, CRealDbEventsSink,&DIID__IRealDbEvents,&LIBID_GSTREALDBLib,1,0> { public:HWND m_hWnd;CRealDbEventsSink(){};virtual ~CRealDbEventsSink(){};BEGIN_SINK_MAP(CRealDbEventsSink) // ATL宏映射事件函数 SINK_ENTRY_EX(1, DIID__IRealDbEvents, 1, OnDbInitialize) SINK_ENTRY_EX(1, DIID__IRealDbEvents, 2, OnDbItemAdded) SINK_ENTRY_EX(1, DIID__IRealDbEvents, 3, OnDbItemDeleted) SINK_ENTRY_EX(1, DIID__IRealDbEvents, 4, OnDbItemChanged) SINK_ENTRY_EX(1, DIID__IRealDbEvents, 5, OnDbItemStateChanged)END_SINK_MAP()HRESULT _stdcall OnDbInitialize();HRESULT _stdcall OnDbItemAdded(IRealDbItem *item);HRESULT _stdcall OnDbItemDeleted(IRealDbItem *item);HRESULT _stdcall OnDbItemChanged(IRealDbItem *item);HRESULT _stdcall OnDbItemStateChanged(IRealDbItem *item, DEVICE_STATE enumOldState, DEVICE_STATE enumNewState);};2、函数定义HRESULT _stdcall CRealDbEventsSink::OnDbInitialize(){::PostMessage(m_hWnd,WM_REALDB_INIT,0,0);return S_OK;}HRESULT _stdcall CRealDbEventsSink::OnDbItemAdded(IRealDbItem *item){return S_OK;}HRESULT _stdcall CRealDbEventsSink::OnDbItemDeleted(IRealDbItem *item){return S_OK;}HRESULT _stdcall CRealDbEventsSink::OnDbItemChanged(IRealDbItem *item){return S_OK;}HRESULT _stdcall CRealDbEventsSink::OnDbItemStateChanged(IRealDbItem *item,DEVICE_STATE enumOldState,DEVICE_STATE enumNewState){return S_OK;}3、定义组件对象指针IRealDb* m_pRealDb;IRealDbItem* m_pRealDbItem;IUnknown* m_pRealDbUnk; //IUnknown指针CRealDbEventsSink *m_pRealDbEventsSink; //接口事件指针4、HRESULT hr;hr=::CoCreateInstance(CLSID_RealDb,NULL,CLSCTX_INPROC_SERVER,IID_IRealDb,(void**)&m_pRealDb);//创建实例if(!SUCCEEDED(hr)){ AfxMessageBox("Create RealDb Instance failed!"); return FALSE;}m_pRealDb->QueryInterface(IID_IRealDb,(void**)&m_pRealDbUnk); //查询接口m_pRealDbEventsSink = new CRealDbEventsSink(); hr = m_pRealDbEventsSink->DispEventAdvise(m_pRealDbUnk);//查询事件if (!SUCCEEDED(hr)) {AfxMessageBox("DispEventAdvise Failed.");return false;}m_pRealDbEventsSin->m_hWnd=this->m_hWnd;