這一篇詳細講述webBrowser 和 js 的雙向通信。 這是樓主遇到的最關鍵的問題,首先看下C#代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
namespace GoogleMap_1
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("addLine");
}
private void button2_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("initialize");
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
}
public String getLat_1()
{
return txtLat_1.Text;
}
public String getLng_1()
{
return txtLng_1.Text;
}
public String getLat_2()
{
return txtLat_2.Text;
}
public String getLng_2()
{
return txtLng_2.Text;
}
}
}
而爲了能與JS交互,首先引入using System.Security.Permissions;,然後在namespace下必須加入兩行
<span style="font-size:18px;"> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]</span>
<span style="font-size:18px;"><pre name="code" class="csharp"> webBrowser1.ObjectForScripting = this;</span>
其中,只有當ComVisibleAttribute爲true時,纔會在webBrowser中加載window.external的運行結果。
而webBrowser1.ObjectForScripting屬性的作用是:獲取或設置一個對象,該對象可由顯示在 WebBrowser 控件中的網頁所包含的腳本代碼訪問。可在html中使用window.external調用本form中的方法。
所以說ComVisibleAttribute,ObjectForScripting,window.external 三者缺一不可。
這樣與js交互的準備工作就ok了,在js中就可以使用window.external直接調用winform中的方法。
如上一篇html代碼中
var myLat = window.external.getLat_1();
var myLng = window.external.getLng_1();
var myPoint_1 = new google.maps.LatLng(myLat,myLng);
獲取txtbox中輸入的值。
這裏樓主當時腦抽了,一直糾結怎樣從html中直接調用winform中的變量,浪費了很多時間和精力,其實就這樣封裝一下,然後調用get方法就行了。還有百度上說的很多的建立public變量再用<%=%>是不能在html靜態頁面使用的。
這樣,項目要求的功能基本就實現了,這是樓主的第一個項目,也是第一次寫博客,希望能給大家帶來幫助。
參考的大牛博客:http://blog.csdn.net/kkkkkxiaofei/article/details/8645856
http://www.cnblogs.com/liuzhendong/archive/2012/03/21/2409159.html
http://blog.csdn.net/wonsoft/article/details/5196837