现在很多软件都做成了内嵌浏览器的形式,vs2008中的webbrwser控件即可以实现此功能。当然不能说2008中的webbrowser是个新东西,他只不过将以前的msthml做了一次不完全封装。姑且不论其封装的如何,至少我们在使用它时不需要向以前一样频繁的调用令人讨厌的IHTMLDocument、IHTMLDocument2、IHTMLDocument3、IHTMLDocument4..........而且新版的webbrowser是线程安全的!这点最重要。

以下代码片段均摘自我的一个项目。

1.下面看看webbrowser如何调用调用页面里的Javascript:

C#段:

代码
void ShowTable(string sid) {
            SetWebBorserSafe(webBrowser1, 
"Showdisplay", sid);
        }
 
public void SetWebBorserSafe(object o,string s,string tag)//保证线程安全
        {
            
if (o == webBrowser1)
            {
                
if (this.webBrowser1.InvokeRequired)
                {
                    BeginInvoke(
new SetWebBroserCallback(SetWebBorserSafe), new object[] { webBrowser1, s, tag });
                }
                
else
                {
                    webBrowser1.Document.InvokeScript(s, 
new String[] { tag});
                }
            }
        
        }

 

去掉干扰代码其实最关键的代码是:

 

webBrowser1.Document.InvokeScript(s, new String[] { tag});

 

 

JavaScript段:

 

   function Showdisplay(id) {

       
if (document.getElementById(id)) {
           
var traget = document.getElementById(id);
           traget.style.display 
= "";
       }
   }

 

上面的代码实现了在C#程序中输入页面的ID号,页面中的对应ID的元素显示功能。

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

2.JavaScript调用C#程序

反向调用有点小步骤

  a.C#代码段让JavaScript能够看见接口

[ComVisible(true)]   //com接口可见
    public partial class FormPD : Form
    {
...............
}

 

  b.C#代码段让寄宿的脚本能够访问

private void FormPD_Load(object sender, EventArgs e)
{
    webBrowser1.ObjectForScripting 
= this;
}

 

当然你也可以把 webBrowser1.ObjectForScripting = this; 写在窗口初始化代码里。
 c.JavaScript和网页的相关代码

代码
<script type="text/javascript"> 
  function getSel() {
       var t
="";
       t
= window.getSelection ? window.getSelection() : (document.getSelection ? document.getSelection() : (document.selection ? document.selection.createRange().Text : ""))
       window.external.ShowPrint(
"实时数据",t);
   }
</script>
<body onmouseup="getSel()">

 

关键代码:  window.external.ShowPrint("实时数据",t);

d.C#代码段

代码
public void ShowPrint(string fromname,string selecthtmltext)
    {
        
//"实时数据",t
        FormSavePrint f = new FormSavePrint("实时数据",selecthtmltext);
         f.MdiParent 
= formmain;
         f.Show();
    }

 

OK!上面可以实现当鼠标选中网页的某些区域时,此区域的页面代码被传入到C#程序的新窗口中。

总体说来比以前的mshtml使用要方便多了

posted on 2010-03-06 09:52  coffeeliu  阅读(1068)  评论(0编辑  收藏  举报