com可连接对象的实现

类别:VC语言 点击:0 评论:0 推荐:

      近来学习 com技术,觉得可连接对象实现起来很难.经过拜读潘老师的书籍,用ATL写出了一个简单例子:
  一  com组件方:
             声明要实现的可连接对象

 [
  uuid(87EA0963-F479-4ABC-95DD-DF0F081B73D2),
  helpstring("LJ Class")
 ]
    interface _IWLEvents:IUnknown
 { 
  [  helpstring("method tongku")] HRESULT JINGJING();
 };
           在类中声明
coclass LJ
 {
  [default] interface ILJ;
  [source] interface _IWLEvents;
 };
 下一步用ATL生成可连接对象,ATL自动生成了 函数JINGJING 的激活方式,如下所示:
class CProxy_IWLEvents : public IConnectionPointImpl<T, &IID__IWLEvents, CComDynamicUnkArray>
{
 //Warning this class may be recreated by the wizard.
public:
 HRESULT Fire_JINGJING()
 {
  HRESULT ret;
  T* pT = static_cast<T*>(this);
  int nConnectionIndex;
  int nConnections = m_vec.GetSize();
  //遍历所以连接上来的客户端
  for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++)
  {
   pT->Lock();        
   CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex);
   pT->Unlock();
   _IWLEvents* p_IWLEvents = reinterpret_cast<_IWLEvents*>(sp.p);
   if (p_IWLEvents != NULL)
    ret = p_IWLEvents->JINGJING();  //调用客户端程序,和客户端发生关联
  } return ret;
 
 }
};
二 客户端
    在客户端用一个对话框程序实现,首先要实现接口IWLEvents的类
class CIWL:public _IWLEvents
{  
  STDMETHODIMP QueryInterface (REFIID iid,LPVOID *pp)
 {
  *pp =this;
  return S_OK;
 }
  STDMETHODIMP_(ULONG) AddRef()
 {
  return 2;
 }
 
 STDMETHODIMP_(ULONG) Release ()
 {
  return 1;
 }
    STDMETHODIMP JINGJING()
 {
    AfxMessageBox(“返回到客户端“);
   return 1;
 }
};
用一个button事件实现调用过程:
void CShowDlg::OnButton1()
{
 CoInitialize(NULL);
 ILJ * p;
 IConnectionPointContainer  * pContainer=NULL;
 IConnectionPoint *pPoint = NULL;
 
 HRESULT hr = CoCreateInstance(CLSID_LJ,NULL,CLSCTX_INPROC_SERVER , IID_ILJ,(void**)&p );
    if(SUCCEEDED(hr))
 {
  p->QueryInterface(IID_IConnectionPointContainer,(void**)&pContainer);
  if(SUCCEEDED(hr))
  {
              
      hr = pContainer->FindConnectionPoint(IID__IWLEvents, &pPoint);
   if(SUCCEEDED(hr))
   {
    DWORD dwCookie;
        CIWL  * m_pDuckInt = new  CIWL ;
       hr =pPoint->Advise(m_pDuckInt,&dwCookie);
    if(SUCCEEDED(hr))
    {
     p-> Fire() ;
     pPoint->Release();
    }
    pPoint->Unadvise(dwCookie);
    
       
   
      }
  CoUninitialize();
 
}

       本人是新手,希望各位老鸟们多多指教阿














本文地址:http://com.8s8s.com/it/it642.htm