IE高亮网页中的关键字

园子里有人写过在WebBrowser 控件里高亮关键字的方法。在此基础上我简单修改实现了直接在IE中高亮关键字。

下面是简单实例,高亮新浪首页的“奥运”关键字 

注意引用 mshtml和SHDocVw

 

 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.ComponentModel;
 4  using  System.Data;
 5  using  System.Drawing;
 6  using  System.Text;
 7  using  System.Windows.Forms;
 8  using  System.IO;
 9  using  mshtml;
10  using  SHDocVw;
11 
12  namespace  WebIntlTest
13  {
14       public   partial   class  Form1 : Form
15      {   
16           private  SHDocVw.InternetExplorer IE;
17           private  DWebBrowserEvents2_DocumentCompleteEventHandler docCompleteHandler;
18 
19           public  Form1()
20          {
21              InitializeComponent();
22          }
23 
24           private   void  Button1_Click( object  sender, EventArgs e)
25          {
26             
27              IE  =   new  InternetExplorer(); 
28              IE.Visible  =   true ;
29               string  URL  =   " http://www.sina.com.cn "
30               object  nullArg  =   null ;
31              IE.Navigate(URL,  ref  nullArg,  ref  nullArg,  ref  nullArg,  ref  nullArg);
32              docCompleteHandler  =   new  DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
33              IE.DocumentComplete  +=  docCompleteHandler;
34              
35          }
36 
37           private   void  ie_DocumentComplete( object  pDisp,  ref   object  URL)
38          {
39 
40             mshtml.IHTMLDocument2 htmlDoc  =  (mshtml.IHTMLDocument2)IE.Document;
41             
42               string  tagBefore  =   " <span style='background-color:yellow;color:black'> " ;
43               string  tagAfter  =   " </span> " ;
44 
45               string  keyword  =   " 奥运 " ;
46               if  (keyword  ==   "" )
47                   return ;
48              IHTMLSelectionObject oTxtrange  =  htmlDoc.selection;
49              IHTMLTxtRange txtrange  =  (IHTMLTxtRange)oTxtrange.createRange();
50 
51               while  (txtrange.findText(keyword,  1 4 ))
52              {
53                   try
54                  {
55                      txtrange.pasteHTML(tagBefore  +  keyword  +  tagAfter);
56                  }
57                   catch  { }
58                  txtrange.collapse( false );
59              } 
60          }
61      }
62 
63  }
64 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值