Webbrowser控件加載html頁面很是簡單。首先拖一個webbrowser控件到窗體中,而後經過代碼:webBrowser1.Navigate("cityApi.html");加載網頁資源。javascript
若是要實現winform與網頁進行交互須要用到事件webBrowser1_DocumentCompleted(即html文檔加載完成後進行交互):html
winform後臺能夠經過語句:webBrowser1.Document.InvokeScript("loadInfo", new object[] {參數1,...,參數m});調用javascript函數loadInfo,實現將數據傳到網頁中;
javascript函數能夠經過語句:window.external.ShowMsg(str);調用winform後臺函數ShowMsg(string str);
下面的代碼展現一個小例子:
【FrmCityApi.cs】
private void FrmCityApi_Load(object sender, EventArgs e) { webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted); //初始化webbrowser,保證js和C#的通訊 webBrowser1.ObjectForScripting = this; //加載webbrowser網頁資源 webBrowser1.Navigate("cityApi.html"); } /// <summary> /// webbrowser文檔加載完畢以後加載空氣指數信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { if (webBrowser1.Document != null) { //加載空氣指數信息 webBrowser1.Document.InvokeScript("loadInfo", new object[] { city_name, api_date.ToString(), api.ToString(), sitenum.ToString() }); } } catch (Exception) { DialogHelper.DlgWarn(this, "加載空氣指數信息錯誤"); } }
【cityApi.html】
<script type="text/javascript"> /* function Run(str) { window.external.ShowMsg(str); }*/ function loadInfo(cityName, apiDate, apidata, num) { document.getElementById("city_name").innerHTML = cityName; document.getElementById("api_time").innerHTML = "數據更新時間:" + apiDate; document.getElementById("city_api_data").innerHTML = apidata; document.getElementById("sites_count").innerHTML = num + "個監測點"; } </script>結束!!!