ActiveX中调用Script函数的方法
Q: ActiveX中如何调用Script函数?如何访问Document,Browser,浏览器地址...
A:
在ATL写的ActiveX中,重载IOleObject::SetClientSite()方法。ms-kb:181678
在MFC写的ActiveX中,重载COleObject::OnSetClientSite()方法。ms-kb:153582
// 调用网页中的javascipt:window.close()函数
void CMyCtrl::OnSetClientSite() {
try {
LPOLECLIENTSITE pClientSite = GetClientSite();
if(pClientSite == NULL) return;
IServiceProvider *isp = NULL;
HRESULT hr = pClientSite->QueryInterface(IID_IServiceProvider, reinterpret_cast<void **>(&isp));
if (FAILED(hr)) return;
IServiceProvider *isp2 = NULL;
hr = isp->QueryService(SID_STopLevelBrowser, IID_IServiceProvider, reinterpret_cast<void **>(&isp2));
isp->Release();
if (FAILED(hr)) return;
IWebBrowser2* browser = NULL;
hr = isp2->QueryService(SID_SWebBrowserApp, IID_IWebBrowser2, reinterpret_cast<void **>(&browser));
isp2->Release();
if (FAILED(hr)) return;
IHTMLDocument* doc = NULL;
hr=browser->get_Document((IDispatch**)&doc);
browser->Release();
if(FAILED(hr)) return;
IDispatch* script = NULL;
hr=doc->get_Script(&script);
doc->Release();
if(FAILED(hr)) return;OLECHAR FAR* sClose = L"close";
DISPID dispid;
hr=script->GetIDsOfNames(IID_NULL,&sClose,1,LOCALE_SYSTEM_DEFAULT,&dispid);
if(FAILED(hr)) return;
DISPPARAMS dpNoArgs = {NULL, NULL, 0, 0};
script->Invoke(dispid,IID_NULL,0,DISPATCH_METHOD,&dpNoArgs,NULL,NULL,NULL);
script->Release();
} catch(...) {
}
}
// 访问浏览器地址
STDMETHOD(SetClientSite)(IOleClientSite *pClientSite) {
if (pClientSite != NULL) {
CComPtr<IMoniker> spmk;
LPOLESTR pszDisplayName;
HRESULT hr = pClientSite->GetMoniker(OLEGETMONIKER_TEMPFORUSER,OLEWHICHMK_CONTAINER,&spmk);
if (SUCCEEDED(hr)) {
hr = spmk->GetDisplayName(NULL, NULL, &pszDisplayName);
if (SUCCEEDED(hr)) {
USES_CONVERSION;
CComBSTR bstrURL;
bstrURL = pszDisplayName;
ATLTRACE("The current URL is %s\n", OLE2T(bstrURL));
CoTaskMemFree((LPVOID)pszDisplayName);
}
}
}
return IOleObject_SetClientSite(pClientSite);
}