利用ATL框架开发BHO浏览器插件网上有不少资料,具体的过程就不写了。参考资料如下:
MSDN:https://msdn.microsoft.com/en-us/library/bb250489(v=vs.85).aspx
CSDN博客:http://blog.csdn.net/feier7501/article/details/11266345
按此种方法生成的插件,当打开网页时会弹出多个MessageBox,就是多次执行了OnDocumentComplete。
解决无果搜索如下文章:
《真正的DocumentComplete》:http://blog.csdn.net/skyremember/article/details/2994168
但代码是VB和MFC的,修改方法如下:
增加CHelloWorldBHO成员变量:
LPUNKNOWN m_lpUnknown;函数SetSite修改如下:
STDMETHODIMP CHelloWorldBHO::SetSite(IUnknown* pUnkSite) { if (pUnkSite != NULL) { // Cache the pointer to IWebBrowser2. HRESULT hr = pUnkSite->QueryInterface(IID_IWebBrowser2, (void **)&m_spWebBrowser); if (SUCCEEDED(hr)) { // Register to sink events from DWebBrowserEvents2. hr = DispEventAdvise(m_spWebBrowser); if (SUCCEEDED(hr)) { m_fAdvised = TRUE; m_lpUnknown = pUnkSite; } } } else { // Unregister event sink. if (m_fAdvised) { DispEventUnadvise(m_spWebBrowser); m_fAdvised = FALSE; m_lpUnknown= NULL; } // Release cached pointers and other resources here. m_spWebBrowser.Release(); } // Call base class implementation. return IObjectWithSiteImpl<CMKeyBHO>::SetSite(pUnkSite); }
OnDocumentComplete函数修改如下:
void STDMETHODCALLTYPE CHelloWorldBHO::OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL) { HRESULT hr; //LPUNKNOWN lpUnknown; LPUNKNOWN lpUnknownWB = NULL; LPUNKNOWN lpUnknownDC = NULL; //lpUnknown = m_spWebBrowser->GetControlUnknown(); //ASSERT(lpUnknown); if (m_lpUnknown) { // Get the pointer to the IUnknown interface of the WebBrowser // control being hosted. The pointer to the IUnknown returned from // GetControlUnknown is not the pointer to the IUnknown of the // WebBrowser control. It's actually a pointer to the IOleObject. // hr = m_lpUnknown->QueryInterface(IID_IUnknown, (LPVOID*)&lpUnknownWB); if (FAILED(hr)) return; // Get the pointer to the IUnknown of the object that fired this // event. // hr = pDisp->QueryInterface(IID_IUnknown, (LPVOID*)&lpUnknownDC); //ASSERT(SUCCEEDED(hr)); if (SUCCEEDED(hr) && lpUnknownWB == lpUnknownDC) { // The document has finished loading. // MessageBox(NULL, L"The document has finished loading.", L"", MB_OK); } if (lpUnknownWB) lpUnknownWB->Release(); if (lpUnknownDC) lpUnknownDC->Release(); } }这样改之后在网页加载完成的时才会弹出对话框,大功告成!