遇到一个问题:在用WebBrowser控件打开网页后,让网页中的滚动条滚动到最底部。
在网上找到了方法:用DCOM组件技术,获取HTML接口指针。(前一阵做调用网页中的JavaScript函数也是采用这种技术)。代码如下:
boolput_scrollTop()
{
HRESULT hr;
CComPtr <IDispatch > spDisp;
IHTMLDocument2 *spDoc = NULL;
spDisp = m_objWebBrowser.GetDocument();
hr = spDisp->QueryInterface( IID_IHTMLDocument2, ( void** )&spDoc );
ASSERT( SUCCEEDED( hr ) );
IHTMLElement* pElement = NULL;
hr = spDoc->get_body( &pElement );
ASSERT( SUCCEEDED( hr ) );
IHTMLElement2* pElement2 = NULL;
hr = pElement->QueryInterface( IID_IHTMLElement2, ( void** )&pElement2 );
ASSERT( SUCCEEDED( hr ) );
// 获得网页中滚动条的全部高度
long scrollTop;
pElement2->get_scrollHeight( &scrollTop );
// 设置滚动条与顶端的偏移量
pElement2->put_scrollTop( scrollTop );
}
在实现的过程中又发现另外一个问题,对于有多个Frame的网页,上面的方法不好用,于是采用了下面的方法:
boolput_scrollTop( IDispatch* pDisp )
{
HRESULT hr;
IHTMLDocument2 *spDoc = NULL;
IHTMLElementCollection* pCollection;
hr = pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&spDoc );
if ( FAILED( hr ) )
{
return false;
}
hr = spDoc->get_all(&pCollection);
if ( FAILED( hr ) )
{
return false;
}
long len;
hr = pCollection->get_length(&len);
if ( FAILED( hr ) )
{
return false;
}
// 遍历所有的元素
for (long l=0; l <len; l++)
{
VARIANT varIndex, var2;
VariantInit(&varIndex);
VariantInit(&var2);
varIndex.vt = VT_I4;
varIndex.lVal = l;
IDispatch* spDisp = NULL;
pCollection->item( varIndex, var2, &spDisp );
IHTMLElement* pElem;
spDisp->QueryInterface( IID_IHTMLElement, (LPVOID*) &pElem );
CComBSTR tagName;
pElem->get_tagName(&tagName);
CString str = tagName;
str.MakeUpper();
//if ( str.Compare( _T( "IFRAME" ) ) == 0 || str.Compare( _T( "FRAME" ) ) == 0 )
{
IHTMLElement2* pElement2 = NULL;
hr = pElem->QueryInterface( IID_IHTMLElement2, ( void** )&pElement2 );
if ( FAILED( hr ) )
{
return false;
}
long lScrollHeight;
hr = pElement2->get_scrollHeight( &lScrollHeight );
if ( FAILED( hr ) )
{
return false;
}
hr = pElement2->put_scrollTop( lScrollHeight );
if ( FAILED( hr ) )
{
return false;
}
pElement2->Release();
}
pElem->Release();
spDisp->Release();
}
pCollection->Release();
spDoc->Release();
return true;
}