C#WinForm与JS通讯

1 篇文章 0 订阅

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>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值