BHO (Browser Helper object) is a simple ATL COM object, and Internet Explorer loads it every time it is run; in other words, an instance of each Internet Explorer loads it. BHO runs in the address space of Internet Explorer, performs any action on accessible objects such as Windows, modules, and so on, and because it is attached to the browser's main window, its lifetime is consistent with the lifetime of the browser instance.
If Active Desktop is turned on in the system, BHO can also be started with Windows Explorer. If you do not want to run BHO in Windows Explorer, you can add the following code to DllMain:
TCHAR strLoader[MAX_PATH];
::GetModuleFileName (NULL, strLoader, MAX_PATH);
if(stricmp("explorer.exe", strLoader) == 0)
return FALSE;
BHO COM server must implement IObjectWithSite so that objects can hook up to browser events, Internet Explorer relies on IObjectWithSite to pass a pointer to its IUnknown interface, so Just implement the IObjectWithSite SetSite method, as follows:
STDMETHODIMP CBhoApp::SetSite(IUnknown *pUnkSite)
{
//获取并存储IWebBrowser2指针
m_spWebBrowser2 = pUnkSite;
if (m_spWebBrowser2 == NULL)
return E_INVALIDARG;
//获取并存储IConnectionPointerContainer指针
m_spCPC = m_spWebBrowser2;
if (m_spCPC == NULL)
return E_POINTER;
//连接到宿主程序以接收事件通知
return Connect();
}
The following is a relatively simple implementation of the Connect function:
HRESULT CBhoApp::Connect()
{
HRESULT hr;
CComPtr<IConnectionPoint> spCP;
//获取访问WebBrowser事件的连接指针
hr = m_spCPC->FindConnectionPoint(DIID_DWebBrowserEvents2, &spCP);
if (FAILED(hr))
return hr;
//把事件处理程序传递给宿主程序Each time an event
//每次有事件产生时,宿主程序都会调用我们实现的IDispatch接口的函数
hr = spCP->Advise(reinterpret_cast<IDispatch*>(this),&m_dwCookie);
return hr;
}