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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM