1. 程式人生 > >winform 與 html 互動 簡單案例

winform 與 html 互動 簡單案例

本文主要簡單的記錄winform如何與html檔案中的資訊如何進行互動,即在winform中載入html介面,從而可以進行相互呼叫。

1.新建一個winform專案,若要在winform中載入html,需要一個webBrowser控制元件。

2.新建一個html頁面,這裡命名為“test.htm”.

3.c#程式碼:

複製程式碼
//為了使網頁能夠與winform互動 將com的可訪問性設定為真
 [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust
")] [System.Runtime.InteropServices.ComVisibleAttribute(true)] public void Hello() { MessageBox.Show("OK,html在呼叫wf中的函式"); } private void Form1_Load(object sender, EventArgs e) { this.webBrowser1.ObjectForScripting = this; string path = Application.StartupPath + @"\test.htm"; //MessageBox.Show(path);
//this.webBrowser1.Navigate(path); this.webBrowser1.Url = new System.Uri(path, System.UriKind.Absolute); }
複製程式碼

4.html程式碼:

複製程式碼
<html>
    <head>
        <title>this is a test</title>
        <script type ="text/javascript">
            function Hello() {
                 window.external.Hello();
//getDebugPath()為c#方法 //alert("hello"); } </script> </head> <body> <button id="btn" onclick="Hello()">hello</button> </body> </html>
複製程式碼

5.結果:這裡算是簡單的完成了在winform中載入html,並在js中呼叫了c#中的資訊。


6.為了方便,直接在上面的基礎上實現在winform中呼叫html中的js函式。關鍵點:this.webBrowser1.Document.InvokeScript("js 的函式名", 引數");

7.c#程式碼:直接拖動一個button控制元件到頁面中。

private void button1_Click(object sender, EventArgs e)
{
    this.webBrowser1.Document.InvokeScript("WfToHtml");
}

8.js程式碼:

<script type ="text/javascript">
    function WfToHtml() {
        alert("wf呼叫html裡面的js函式");
    }
</script>

9.結果:

初學者,內容也比較簡單,準備再載入一個swf,哈哈。。。