標籤:xhtml org sage c# 注意 nbsp 指令碼 .text init
C# windows程式應用與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 WinFormJSDemo11 {12 //設定Com對外可訪問13 [System.Runtime.InteropServices.ComVisible(true)]14 public partial class Form1 : Form15 {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
C# windows程式應用與JavaScript 程式互動實現例子