C# windows程序应用与JavaScript 程序交互实现例子

C# windows程序应用与JavaScript 程序交互实现例子

最近项目中又遇到WinForm窗体内嵌入浏览器(webBrowser)的情况,而且涉及到C#与JavaScript的相互交互问题,下面就是一个交互例子,仅供参考

一、建立网页代码(包含js方法代码和访问外部windows应用事件)

这里需要注意js访问外部windows应用程序方法,需要代用windows对象的external

例子:window.external.CSharpfunction(xx,xx,xx);
 1 <!DOCTYPE html>
 2 
 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <meta http-equiv="Content-Language" content="zh-cn">
 6     <script language="javascript" type="text/javascript">
 7               <!-- 提供给C#程序调用的方法 -->
 8               function messageBox(message)
 9               {
10                     alert(message);
11              }
12     </script>
13 </head>
14 
15 <body>
16     <!-- 调用C#方法 -->
17     <button onclick="window.external.MyMessageBox('javascript访问C#代码')">
18         javascript访问C#代码
19     </button>
20 </body>
21 </html>

二、创建C#windows窗体应用

代码:需要注意的是需要给form1类加上对com的可访问性设置  [System.Runtime.InteropServices.ComVisible(true)]

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace WinFormJSDemo
11 {
12     //设置Com对外可访问
13     [System.Runtime.InteropServices.ComVisible(true)]
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19             System.IO.FileInfo file = new System.IO.FileInfo("JavaScript//index.html");
20 
21             // WebBrowser控件显示的网页路径
22             webBrowser1.Url = new Uri(file.FullName);
23 
24             // 将当前类设置为可由脚本访问
25             webBrowser1.ObjectForScripting = this;
26         }
27 
28 
29         //被外部js调用的方法
30         public void MyMessageBox(string message)
31         {
32 
33             MessageBox.Show(message);
34         }
35 
36         private void button1_Click(object sender, EventArgs e)
37         {
38             // 调用JavaScript的messageBox方法,并传入参数
39             object[] objects = new object[1];
40 
41             objects[0] = "C#访问JavaScript脚本";
42 
43             webBrowser1.Document.InvokeScript("messageBox", objects);
44         }
45     }
46 }

运行结果:

C#调用JavaScript方法

JavaScript调用C#方法:

源代码工程文件下载

参考:http://www.cnblogs.com/xds/archive/2007/03/02/661838.html

原文地址:https://www.cnblogs.com/JiYF/p/7976391.html