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 οnclick="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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章