[置顶] 像VB一样在VC中隐式调用COM(VC的后期绑定方式)

 1.创建COM对象(comdll.classname)

IDispatch* CreateClassComDispatch(BSTR sClassName) { CLSID clsid; IUnknown *pUnk; IDispatch *pDisp; HRESULT hr; CLSIDFromProgID(sClassName, &clsid); hr = CoInitialize(NULL); if(FAILED(hr)) return FALSE; hr = CoCreateInstance(clsid,NULL,CLSCTX_ALL,IID_IUnknown,(void**)&pUnk); if(FAILED(hr)) return FALSE; hr = pUnk->QueryInterface(IID_IDispatch, (void **)&pDisp); if(FAILED(hr)) { pUnk->Release(); return FALSE; } return pDisp; }

2.调用

BOOL retValue; HRESULT hr; DISPID idd; VARIANTARG varResult; IDispatch *pDisp; try { VariantInit(&varResult); retValue = TRUE; //对应组件 _bstr_t bstrCom = _bstr_t(libName); pDisp = CreateClassComDispatch(bstrCom); if(pDisp == NULL) return NULL; //方法名 LPOLESTR str = L"......."; //参数初始化 int ParamsNumber = 2; VARIANTARG avarParams[2]; for(int i=0;i<ParamsNumber;i++){ ::VariantInit( &avarParams[i] ); } _bstr_t bstrTemp = _bstr_t(lpPassword); avarParams[0].vt = VT_BSTR; avarParams[0].bstrVal = bstrTemp.copy(); _bstr_t bstrTemp1 = _bstr_t(lpFileName); avarParams[1].vt = VT_BSTR; avarParams[1].bstrVal = bstrTemp1.copy(); DISPPARAMS params = { avarParams, NULL, ParamsNumber, 0 }; //得到ID hr = pDisp->GetIDsOfNames(IID_NULL,&str,1,NULL,&idd); if(!FAILED(hr)) { hr = pDisp->Invoke(idd, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &params, &varResult, NULL, NULL); if(FAILED(hr)) retValue = FALSE; } else { retValue = FALSE; } for(int j=0;j<ParamsNumber;j++){ ::VariantClear( &avarParams[j] ); } ::VariantClear(&varResult); if(!retValue) return NULL; else return (HBITMAP)varResult.lVal; } catch(...) { } return NULL;

3.释放

::CoUninitialize();

你可能感兴趣的:(user,null,vb)