winform嵌入谷歌地图,实现webBrowser和js的双向通信(二)

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


由c#调用js中的方法比较简单,用webBrowser1.Document.InvokeScript() 方法就能实现。

为了能与JS交互,首先引入using System.Security.Permissions;,然后在namespace下必须加入两行

<span style="font-size:18px;">    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]</span>


然后在form1_load中写入
<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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值