Wednesday, November 14, 2007

How to get a handle to current TabWindowClass tab in IE7

IWebBrowser2::get_HWND method gets the handle of the Internet Explorer 7 main window. Sometimes the tab window handle is needed. Here's a sample code that I recently found in MSDN. It shows how to get the handle of the tab window starting from a IWebBrowser2 object.
#include <shlguid.h>

HWND GetTabWnd(CComQIPtr<IWebBrowser2> spBrowser)
{
HWND hwndTab = NULL;
CComQIPtr<IServiceProvider> spServiceProvider = spBrowser;

if (spServiceProvider != NULL)
{
CComQIPtr<IOleWindow> spWindow;
if (SUCCEEDED(spServiceProvider->QueryService(
SID_SShellBrowser,
IID_IOleWindow,
(void**)&spWindow)))
{

spWindow->GetWindow(&hwndTab));
}
}

return hwndTab;
}
I think the code is supposed to work on top level IWebBrowser2 objects. You can read more about top browser objects in my previous article.

This technique was successfully implemented and tested in Twebst web automation library.

3 comments:

shadow said...

I tried to use this to get the handle of my IWebBrowser2. But the handle still does not respond to SetFocus. :(

Do you know of how I can set the focus to my iwebbrowser2 or the ie instance?

Ppredicament: I have an IWebBrowser2 inside a CAxWindow. When the app starts and the browser navigates to the start page, the user must click the mouse in the browser control window in order to get the mousewheel scrolling and keyboard navigation to work. I need to make the browser focused so it receives my keyboard inputs without having to click at the start.

shadow said...

i never found a good work-around for this.

what i did is i faked a mouse event to the CAxWindow after page navigation so it gets selected/focused. keyboard works after that.

for anyone looking, here it is (lame work-around, but worked)

m_HostWnd.SendMessageToDescendants(WM_LBUTTONDOWN, 0, NULL);
//m_HostWnd is CAxWindow, i just placed NULL at the last part, i think it's supposed to be //the mouse position..

CodeCentrix said...

I think that IWebBrowser2.HWND returns the top level window handle of your application when borwser control is hosted.

So you need to call SetFocus agains "Internet Explorer_Server" window.