JavaScript與C# Windows應用程序交互方法


一、建立網頁 


<html> 
<head> 
      <meta http-equiv="Content-Language" content="zh-cn"> 
      <script language="javascript" type="text/javascript"> 
             <!-- 提供給C#程序調用的方法 --> 
             function messageBox(message) 
             { 
                   alert(message); 
            } 
      </script> 
</head> 

<body> 
      <!-- 調用C#方法 --> 
      <button onclick="window.external.MyMessageBox('javascript訪問C#代碼')" > 
      javascript訪問C#代碼</button> 
</body> 
</html> 


二、建立Windows應用程序 

1.       創建Windows應用程序項目 

2.       在Form1窗體中添加WebBrowser控件 

3.       在Form1類的上方添加 

[System.Runtime.InteropServices.ComVisibleAttribute(true)] 

這是為了將該類設置為com可訪問。如果不進行該聲明將會出錯。出錯信息如下圖所示: 



如: 

[System.Runtime.InteropServices.ComVisibleAttribute(true)] 

public partial class Form1 : Form 



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); 
   } 


免責聲明!

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



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