首先创建网页:javascript
<html> <head> <meta http-equiv="Content-Language" content="zh-cn"> <script language="javascript" type="text/javascript"> <!-- 提供给C#程序调用的方法 --> function messageBox(message) { alert(message); } </script> </head> html
<body> <!-- 调用C#方法 --> <button onclick="window.external.MyMessageBox('javascript访问C#代码')" > javascript访问C#代码</button> </body> </html> java
2、创建Windows应用程序web
建立Windows应用程序项目
在Form1窗体中添加WebBrowser控件
在Form1类的上方添加
[System.Runtime.InteropServices.ComVisibleAttribute(true)]ui
这是为了将该类设置为com可访问。若是不进行该声明将会出错。出错信息以下图所示:this
如:code
[System.Runtime.InteropServices.ComVisibleAttribute(true)]orm
public partial class Form1 : Formhtm
4.初始化WebBrowser的Url与ObjectForScripting两个属性。对象
Url属性:WebBrowser控件显示的网页路径
ObjectForScripting属性:该对象可由显示在WebBrowser控件中的网页所包含的脚本代码访问。
将Url属性设置为须要进行操做的页的URL路径。
JavaScript经过window.external调用C#公开的方法。即由ObjectForScripting属性设置的类的实例中所包含的公共方法。具体设置例子以下:
System.IO.FileInfo file = new System.IO.FileInfo("index.htm");
// WebBrowser控件显示的网页路径
webBrowser1.Url = new Uri(file.FullName);
// 将当前类设置为可由脚本访问
webBrowser1.ObjectForScripting = this;
5.C#调用JavaScript方法
经过WebBrowser类的Document属性中的InvokeScript方法调用当前网页的Javascript方法。如:
// 调用JavaScript的messageBox方法,并传入参数
object[] objects = new object[1];
objects[0] = "C#访问JavaScript脚本";
webBrowser1.Document.InvokeScript("messageBox", objects);
完整代码以下:
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); System.IO.FileInfo file = new System.IO.FileInfo("index.htm"); // WebBrowser控件显示的网页路径 webBrowser1.Url = new Uri(file.FullName); // 将当前类设置为可由脚本访问 webBrowser1.ObjectForScripting = this;
}
private void button1_Click(object sender, EventArgs e)
{ // 调用JavaScript的messageBox方法,并传入参数 object[] objects = new object[1]; objects[0] = "C#访问JavaScript脚本"; webBrowser1.Document.InvokeScript("messageBox", objects);
}
// 提供给JavaScript调用的方法
public void MyMessageBox(string message)
{
MessageBox.Show(message);
} }
end.