C# windows程式應用與JavaScript 程式互動實現例子

來源:互聯網
上載者:User

標籤: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 程式互動實現例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.