尝试过各种常规方法去获取,都获取不到,到最后使用JS进行获取了.同时,也提供了一种在VC/C++/MFC下执行网页JS代码的方法.话不多说,看代码:
1 加入头文件:
- #import "C:\\windows\\system32\\msscript.ocx"
- using namespace MSScriptControl;
2 代码实现
- CString runJS(IHTMLDocument2* pDoc)
- {
- //使用前已经初始化com
- ::CoInitialize(NULL);
- HRESULT hr;
- IScriptControlPtr pScriptControl(__uuidof(ScriptControl));
- pScriptControl->Language = "JScript";
- pScriptControl->AllowUI = TRUE;
- CString jsStr = _T("function getScroll()\
- {var t, l, w, h;\
- if (document.documentElement && document.documentElement.scrollTop)\
- {\
- t = document.documentElement.scrollTop;\
- l = document.documentElement.scrollLeft;\
- } \
- else if (document.body)\
- { \
- t = document.body.scrollTop;\
- l = document.body.scrollLeft;\
- } \
- return l+\"|\"+t;\
- } ");
- LPSAFEARRAY psa;
- SAFEARRAYBOUND rgsabound[] = { 1, 0 }; // 1 elements, 0-based
- int i;
- psa = SafeArrayCreate(VT_VARIANT, 1, rgsabound);
- if (!psa)
- {
- return NULL;
- }
- VARIANT vFlavors[1];
- for (i = 0; i < 1; i++)
- {
- VariantInit(&vFlavors[i]);
- V_VT(&vFlavors[i]) = VT_BSTR;
- }
- V_BSTR(&vFlavors[0]) = SysAllocString(L"TC_P");
- long lZero = 0;
- hr = SafeArrayPutElement(psa, &lZero,&vFlavors[0]);
- for(i=0;i<1;i++)
- {
- SysFreeString(vFlavors[i].bstrVal);
- }
- _bstr_t exp = jsStr;
- pScriptControl->AddCode(exp);
- IHTMLDocument2 *objDocument1=NULL;
- IHTMLWindow2* pIHTMLWindow1 = NULL;
- objDocument1 = pDoc;
- if(objDocument1)
- {
- objDocument1->get_parentWindow(&pIHTMLWindow1);
- pScriptControl->AddObject("window", pIHTMLWindow1, VARIANT_TRUE);
- }
- _variant_t outpar = pScriptControl->Run("getScroll", &psa);
- outpar.ChangeType(VT_BSTR,NULL);
- SafeArrayDestroy(psa);
- ::CoUninitialize();
- return outpar.bstrVal;
- }
通过这个方法,就可以滚动条的位置了.至于 IHTMLDocument2* pDoc这个对象,获取方法有很多种,下次我再发获取IHTMLDocument2* 的代码.
如果大家还有什么更好的方法,谢谢一起交流!
转载于:https://blog.51cto.com/binge518/1133098