Introduction
For some time I struggled to do these simple tasks in Visual C++:
- How to get browser window to scroll programmatically?
It does not accept Windows scroll messages. Calling the MFC GetScrollInfo
APIs does not do anything. But there is a way.
- To scroll we use
IHTMLElement2
API get_scrollTop
/put_scrollTop
... but how do I obtain IHTMLElement2
?
The way is a bit obscure...
Now, the code
HRESULT hr;
IDispatch *pDisp = m_browser.GetDocument();
ASSERT( pDisp );
IHTMLDocument2 *pDocument = NULL;
hr = pDisp->QueryInterface( IID_IHTMLDocument2, (void**)&pDocument );
ASSERT( SUCCEEDED( hr ) );
ASSERT( pDocument );
IHTMLElement *pBody = NULL;
hr = pDocument->get_body( &pBody );
ASSERT( SUCCEEDED( hr ) );
ASSERT( pBody );
IHTMLElement2 *pElement = NULL;
hr = pBody->QueryInterface(IID_IHTMLElement2,(void**)&pElement);
ASSERT(SUCCEEDED(hr));
ASSERT( pElement );
pElement->put_scrollTop( 100 );
long scroll_height;
pElement->get_scrollHeight( &s );
long real_scroll_height;
pElement->put_scrollTop( 20000000 );
pElement->get_scrollTop( &real_scroll_height );
real_scroll_height += window_height;
TRACE( "real scroll height: %ld, get_scrollHeight: %ld\n",
real_scroll_height, scroll_height );
And there we have it.