zoukankan      html  css  js  c++  java
  • C#后台程序与HTML页面中JS方法互调

     此方法适用于 C#中嵌入WebBrowser(浏览器) 通过浏览器中加载的页面与C#的后台代码进行交互。
      一、C#程序
      1、在C#窗体中添加WebBrowser(浏览器),将页面的URL添加到浏览器中。
      2、窗体代码添加 using System.Runtime.InteropServices;//和Html页面交互使用
      在类的上一行添加 [ComVisible(true)]//和Html页面交互使用
      在类的构造其中添加
      this.webB.ObjectForScripting = this; //和Html页面交互使用
      如:
      using System.Runtime.InteropServices;
      namespace slgdjb {
      [ComVisible(true)]
      public partial class Frm_Index : Form
      {
      public Frm_Index()
      {
      InitializeComponent();
      this.webB.ObjectForScripting = this;
      }
      }
      }
      3、添加供Html页面调用的方法
      如:
      该方法的方法名即为Html页面JS中所要调用的方法名
      public string myAction(object para) {   //方法内容在此写           }
      4、C#程序调用Html页面JS方法
      首先要获得Html页面的Document,然后再调用Html页面的JS方法
      如:
      HtmlDocument doc = webB.Document; string[] objArray = new string[2]; objArray[0] = "a";
      objArray[1] = "b"; //调用Html页面js方法,JSMonth为JS方法名,objArray为传递的参数。
      //JS中不能接收对象,但可以接收整形、字符串、字符串数组。 doc.InvokeScript("JSMonth",objArray);
      二、Html页面中JS方法调用C#方法
      1、在Html页面JS中调用C#程序的方法,若C#中的方法有返回值,则JS可以得到。
      如:
      //myAction为C#中方法的方法名,para为该方法的参数。
      var str = window.external.myAction(para);
      2、供C#调用的Html页面中JS的方法
      该方法的方法名即为C#中所要调用的方法名  obj即为要传递的参数。若传递的参数为数组,则在JS
      方法中可直接使用arguments[index(数组参数编号)]表示数组的参数值。arguments为JS默认数组参数,其好处在于JS方法不必写传递的参数。
      function JSMonth(obj){
      //若obj为数组,则obj[0]等价于arguments[0];其方法名可改写为JSMonth()
      }

  • 相关阅读:
    动画,缩放
    本地公司
    调研 公司信息
    外贸 内贸 经商
    情感 爱情 恋爱
    H5源码
    世界 生活
    标识
    Jackson
    java数据结构
  • 原文地址:https://www.cnblogs.com/haosola/p/3871031.html
Copyright © 2011-2022 走看看