JS与C#通过WebBrowser互操作

刚阅读到“永不言败”的这篇《JavaScript与C# Windows应用程序交互》,所以打个解决方案包,收藏下来。

JS与C#通过WebBrowser互操作

关键代码如下:

HTML部分:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <mce:style type="text/css"><!-- div { margin: 10px; } p { font-size: small; } --></mce:style><style type="text/css" mce_bogus="1">div { margin: 10px; } p { font-size: small; }</style> <mce:script language="javascript" type="text/javascript"><!-- 提供给C#程序调用的方法 --> function messageBox(message) { alert(message); } // --></mce:script> </head> <body> <div> <!-- 调用C#方法 --> <button onclick="window.external.MyMessageBox('javascript访问C#代码')">javascript访问C#代码 </button></div> <div> <p>原作者:永不言败<br /><a href="http://www.cnblogs.com/xds/archive/2007/03/02/661838.html" mce_href="http://www.cnblogs.com/xds/archive/2007/03/02/661838.html" target="_blank">转到《JavaScript与C# Windows应用程序交互》</a></p><p>日志收藏:Oyi319<br /><a href="http://blog.****.net/oyi319/archive/2010/07/08/5721482.aspx" mce_href="http://blog.****.net/oyi319/archive/2010/07/08/5721482.aspx" target="_blank">转到 Oyi319的博客</a></p></div> </body> </html>

CS代码部分:

using System; using System.IO; using System.Windows.Forms; namespace JsAndCsharp { [System.Runtime.InteropServices.ComVisibleAttribute(true)] public partial class Form1 : Form { public Form1() { InitializeComponent(); Text = @"JS与C#互操作 - WebBrowser"; FileInfo file = new FileInfo("index.htm"); webBrowser1.Url = new Uri(file.FullName); webBrowser1.ObjectForScripting = this; //为Js提供访问的C#类,这个类要求ComVisibleAttribute(true) } private void button1_Click(object sender, EventArgs e) { object[] objects=new object[1]; objects[0] = "C#访问JavaScript脚本"; webBrowser1.Document.InvokeScript("messageBox", objects); //调用Js的messageBox方法 } //Js将会调用此方法 public void MyMessageBox(string message) { MessageBox.Show(message); } } }

-------------

JS与C#通过WebBrowser互操作JsAndCsharp.7z

类型: 7Z 压缩文件
大小: 9 KB
上传时间 2010-7-8 17:40