C#WinForm与JS通讯

来源:互联网 发布:网络销售水果 编辑:程序博客网 时间:2024/05/02 20:34

1、与JS基本通讯原理

CS 代码

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.Runtime.InteropServices;namespace web_and_js{    //基类也要COM可见    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]    [System.Runtime.InteropServices.ComVisibleAttribute(true)]    public partial class 与JS通讯 : Form    {        public 与JS通讯()        {            InitializeComponent();        }        private void 与JS通讯_Load(object sender, EventArgs e)        {            string texturl = Application.StartupPath + "/与JS通讯/text.html";            this.webBrowser1.ObjectForScripting = this;            this.webBrowser1.Navigate(texturl);        }        //外部JS执行函数        public void WinFormMessage(string str)          {            MessageBox.Show(str, "获取JS函数数据:");        }        //外部JS获取函数        public string WinFormRetustr()         {            string str = "您获取到的是C#WinFormRetustr()函数";            return str;        }    }}

HTML代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>C#WinForm与JS通讯</title><script>function GetWinForm(){   //获取C#窗口信息   alert("【取得C#窗口信息】"+window.external);}function GetWinFormRetustr(){   //获取C#窗口信息   alert("【取得C#窗口函数】"+window.external.WinFormRetustr);}function GetJsalert(str){   //向C#窗体内发送数据          window.external.WinFormMessage(str);}</script></head><body><p><input type="button" value="点击测试【取得C#窗口信息】" onClick="GetWinForm();"></p><p><input type="button" value="点击测试【取得C#窗口函数】" onClick="GetWinFormRetustr();"></p><p><input type="button" value="点击测试【C#WinForm获取JS数据】" onClick="GetJsalert('您看到的是从JS传输过来的数据!');"></p></body></html>