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,哈哈。。。

 


免責聲明!

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



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