网页高亮查找还有一种方法,就是调用内核的接口IHTMLTxtRange的方法
要获取到接口 IHTMLTxtRange,需要调用接口IHTMLBodyElement的方法 createTextRange。可采用如下过程:
1.采用IHTMLDocument2接口的get_body方法获取到IHTMLElement接口
2.采用IHTMLElement接口QueryInterface获取到接口IHTMLBodyElement;
3.采用IHTMLBodyElement的方法createTextRange,获取到IHTMLTxtRange
获取到IHTMLTxtRange,就可以查找了,调用findText方法,如果要对查找到的元素高亮的话,需要采用IHTMLTxtRange的方法pasteHTML
附上代码
void CSearchText::SearchText(IHTMLDocument2* pDoc2,SEARCH_INFO1& _info)
{
CComPtr<IHTMLElement> lpBodyElm;
CComPtr<IHTMLBodyElement> lpBody;
HRESULT hr = pDoc2->get_body(&lpBodyElm);
if (FAILED(hr))
{
return;
}
hr = lpBodyElm->QueryInterface(IID_IHTMLBodyElement,(void**)&lpBody);
if (FAILED(hr))
{
return;
}
hr = lpBody->createTextRange(&_info.m_pTxtRange);
if (FAILED(hr))
{
return;
}
long t;
VARIANT_BOOL bFound;
while(_info.m_pTxtRange->findText(m_bszSearchText,0,0,&bFound),bFound)
{
CComPtr<IHTMLElement> pElement;
_info.m_pTxtRange->parentElement(&pElement);
if (CheckElementHide(pElement))
{
_info.m_pTxtRange->moveStart((BSTR)CComBSTR("Character"),1,&t);
_info.m_pTxtRange->moveEnd((BSTR)CComBSTR("Textedit"),1,&t);
continue;
}
InsertMarkup(_info.m_pTxtRange);
_info.m_pTxtRange->moveStart((BSTR)CComBSTR("Character"),1,&t);
_info.m_pTxtRange->moveEnd((BSTR)CComBSTR("Textedit"),1,&t);
m_nCount ++;
_info.m_TotalCount++;
}
}
bool CSearchText::CheckElementHide(IHTMLElement* pElement)
{
if( pElement != NULL )
{
for ( ; ;)
{
CComPtr<IHTMLElement> pParentElement = NULL;
if (S_OK != pElement->get_parentElement(&pParentElement) || NULL == pParentElement)
break;
CComPtr<IHTMLCurrentStyle> pHtmlStyle = NULL;
CComQIPtr<IHTMLElement2, &IID_IHTMLElement2> pIHtmlElement2(pElement);
pIHtmlElement2->get_currentStyle(&pHtmlStyle);
CComBSTR bszDisplay, bszVisible;
if( pHtmlStyle != NULL )
{
pHtmlStyle->get_display(&bszDisplay);
pHtmlStyle->get_visibility(&bszVisible);
}
if (0 == StrCmpI( _T("none") , bszDisplay) || 0 == StrCmpI(_T("hidden") , bszVisible) )
{
return true;
}
pElement = pParentElement;
}
}
return false;
}
void CSearchText::InsertMarkup(CComPtr<IHTMLTxtRange> pTxtRange, bool bfocus)
{
CComBSTR html;
CComBSTR newhtml;
if (bfocus)
{
pTxtRange->scrollIntoView(TRUE);
newhtml.Append("<font id='AliSearch' style='background-color:#00ff00'>");
}
else
{
newhtml.Append("<font id='AliSearch' style='background-color:#fb9131'>");
}
//添加背景色
pTxtRange->get_htmlText(&html);
if(m_bszSearchText==" ")
{
newhtml.Append(" "); // doesn't work very well, but prevents (some) shit
}
else
{
newhtml.AppendBSTR(html);
}
newhtml.Append("</font>");
pTxtRange->pasteHTML(newhtml);
}
碰上有frame的网页,需要递归出frame中的doc,然后再按照这样的方式查找即可