这一篇详细讲述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