1. 程式人生 > >C#中使用Webbrowser控制元件如何傳值

C#中使用Webbrowser控制元件如何傳值

在使用Winform開發時,需要用到Webbrowser控制元件用來展示頁面,如何將控制元件的值傳給頁面呢?

一. 對於少量引數值,可以在url地址中加入需要傳輸的值。前臺頁面js解析url地址引數即可

//C#程式碼,傳輸使用者ID為80的值給testPage.aspx頁面
string url = "localhost:8080//testPage.aspx?userID="+80;
webBrowser1.Navigate(url);
//JS程式碼,讀取url中的userID
userID = GetQueryString("userID");//獲取位址列中的使用者ID
function GetQueryString
(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; }

二. 對於大量資料,比如後臺獲取的大量資料在頁面中用圖展現,可以使用webBrowser的ObjectForScripting屬性。
MSDN上對ObjectForScripting的解釋是:獲取或設定一個物件,該物件可由顯示在 WebBrowser 控制元件中的網頁所包含的指令碼程式碼訪問,一開始看不懂這句話什麼意思,仔細琢磨,其實就是說webBrowser控制元件指向的頁面可以通過頁面的js訪問ObjectForScripting設定的物件,該物件一般設定為後臺物件,這樣就可以使前臺頁面訪問後臺方法。

在設定了webBrowser控制元件的ObjectForScripting屬性後,還需要設定應用程式對com可見,不然會丟擲一個異常 ,可做如下設定:
[System.Runtime.InteropServices.ComVisible(true)]

//C#呼叫視窗
BusinessDataExportFigure bdef = new BusinessDataExportFigure();
bdef.strData = resultStr;//結果資料賦值傳遞
bdef.Show();
//C#後臺程式碼
using System;
using System.Collections.Generic;
using
System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace sample { [System.Runtime.InteropServices.ComVisibleAttribute(true)]//標記對com可見 public partial class BusinessDataExportFigure : Form { public string strData;//用於承接後臺資料 public BusinessDataExportFigure() { InitializeComponent(); } public string GetData() { //供頁面呼叫以傳遞資料 return strData; } private void BusinessDataExportFigure_Load(object sender, EventArgs e) { this.webBrowser1.ObjectForScripting = this;//設定物件為當前BusinessDataExportFigure窗體 string url = "localhost:8080//testPage.aspx"; this.webBrowser1.Navigate(url); } } }

上面程式碼是在一個名稱命名為BusinessDataExportFigure的Form中添加了一個webBrowser控制元件,該webBrowser控制元件指向testPage.aspx頁面

//testPage頁面
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <div>
        <button onclick="showData()">點選檢視</button>
    </div>
</body>
    <script>
        function showData() {
            var data = window.external.GetData();//使用window.external直接呼叫後臺C#方法
            alert(data);
        }
    </script>
</html>

題外話:上面實現了JS呼叫後臺C#方法,那麼C#是否也可以呼叫頁面JS函式呢?
這個是可以的,使用webBrowser控制元件的Document物件的InvokeScript方法即可。
該方法有兩種引數形式

  • InvokeScript(string):string為要執行的指令碼函式的名稱,JS函式不需要引數
  • InvokeScript(string,Object[]):string為要執行的指令碼函式的名稱;Object[]要傳遞到指令碼函式的引數

例如:

//HTML程式碼
<script type="text/javascript"> 
    function sayHello(name,message)
    {             
        alert(name+","+message);    
    }     
</script>

呼叫:

//C#
if(this.loadCompleted)//在文件載入完畢後呼叫
{
    webBrowser1.Document.InvokeScript("sayHello", new Object[] {Tom,"hello"}); 
}

需要注意的一點是,使用InvokeScript方法需要在文件載入完畢後,所以需要檢查文件載入情況