开发学院软件开发VC COM对象与连接点机制及其MFC程序实现 阅读

COM对象与连接点机制及其MFC程序实现

 2010-06-04 20:39:28 来源:WEB开发网   
核心提示:3.实现事件接收器:STDMETHODIMP_(ULONG)CConnClientDlg::XEventSink::AddRef(){return 1;}STDMETHODIMP_(ULONG)CConnClientDlg::XEventSink::Release(){return 0;}STDMETHODIMPCCo

3.实现事件接收器:

STDMETHODIMP_(ULONG)
CConnClientDlg::XEventSink::AddRef()
{
return 1;
}
STDMETHODIMP_(ULONG)
CConnClientDlg::XEventSink::Release()
{
return 0;
}
STDMETHODIMP
CConnClientDlg::XEventSink::QueryInterface(REFIID riid,void** ppvObj)
{
METHOD_PROLOGUE(CConnClientDlg,EventSink)
if(IsEqualIID(riid,IID_IUnknown)||
IsEqualIID(riid,IID_IEventSink))
{
*ppvObj = this;
AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
STDMETHODIMP
CConnClientDlg::XEventSink::EventHandle() //此函数将被可连接对象调用
{
::AfxMessageBox("源对象向事件接收器发出了的通知!");
return S_OK;
}

4.初始化COM库并创建组件对象实例

在CConnClientDlg::OninitDialog()中写入:

HRESULT hResult;
hResult = ::CoInitialize(NULL);
if(FAILED(hResult))
{
::AfxMessageBox("不能初始化COM库!");
return FALSE;
}
m_pIUnknown = NULL;
hResult = ::CoCreateInstance(CLSID_ConnObject,NULL,
CLSCTX_INPROC_SERVER,IID_IUnknown,(void**)&m_pIUnknown);
if(FAILED(hResult))
{
m_pIUnknown = NULL;
::AfxMessageBox("不能创建ConnObject对象!");
return FALSE;
}

m_dwCookie = 0;//预置连接标识为0

5.在按钮”连接”(IDC_CONNECT)的CLICK事件处理函数void CConnClientDlg::OnConnect()中写入:

void CConnClientDlg::OnConnect()
{
if(m_dwCookie!=0)
{
return;
}
if(m_pIUnknown!=NULL)
{
HRESULT hResult;
hResult = m_pIUnknown->QueryInterface(IID_IConnectionPointContainer,
(void**)&pConnPtCont);
if(FAILED(hResult))
{
::AfxMessageBox("不能获取对象的IConnectionPointContainer接口!");
return;
}
ASSERT(pConnPtCont!=NULL);
hResult = pConnPtCont->FindConnectionPoint(IID_IEventSink,&pConnPt);
if(FAILED(hResult))
{
pConnPtCont->Release();
::AfxMessageBox("不能获取对象的IEventSink连接点接口!");
return;
}
ASSERT(pConnPt!=NULL);
//获取事件接收器指针
IUnknown* pIEventSink;
m_xEventSink.QueryInterface(IID_IUnknown,(void**)&pIEventSink);
//通过连接点接口的Advise方法将事件接收器指针传给可连接对象
if(SUCCEEDED(pConnPt->Advise(pIEventSink,&m_dwCookie)))
{
::AfxMessageBox("与可连接对象ConnObject建立连接成功!");
}
else
{
::AfxMessageBox("不能与ConnObject建立连接!");
}
pConnPt->Release();
pConnPtCont->Release();
return;
}
}

上述代码与可连接对象的连接点建立连接.

上一页  1 2 3 4 5  下一页

Tags:COM 对象 连接点

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接