zoukankan      html  css  js  c++  java
  • [Winform-WebBrowser]-在html页面中js调用winForm类方法

       在winform项目中嵌入了网页,想通过html页面调用后台方法,如何实现呢?其实很简单,主要有三部:

    1、在被调用方法类上加上[ComVisible(true)]标签,意思就是当前类可以com组件的形式供外包调用

    2、在webBrowser控件中设置可被html页面调用的类即:webBrowser1.ObjectForScripting = this;前端即可通过window.external访问this对象

    3、html页面调用后台方法:window.external.方法名(); 此处的window.external相当于webBrowser1.ObjectForScripting

     1    //ComVisible 设置对外的可访问性,在html中可使用 js 访问成员方法
     2     [ComVisible(true)]
     3     public partial class Form1 : Form
     4     {
     5         public Form1()
     6         {
     7             InitializeComponent();
     8         }
     9 
    10         private void Form1_Load(object sender, EventArgs e)
    11         {
    12             //browser.Url = new Uri("https://www.baidu.com");
    13             browser.Url = new Uri("http://localhost:3133/index.html");
    14             browser.ObjectForScripting = this;
    15         }
    16 
    17         private void btnSearch_Click(object sender, EventArgs e)
    18         {
    19             HtmlElement kw = browser.Document.All["kw"];
    20             HtmlElement btn = browser.Document.All["su"];
    21 
    22             string txt = txtwd.Text.Trim();
    23             kw.SetAttribute("value", txt);
    24             btn.InvokeMember("click");
    25         }
    26 
    27         private void btnDo_Click(object sender, EventArgs e)
    28         {
    29             int[] arr = { 1, 23 };
    30             browser.Document.InvokeScript("f",new object[] { "{1,2,3}" });
    31         }
    32 
    33         public void WinF(string arg)
    34         {
    35             MessageBox.Show(arg);
    36         }
    37     }

    html 代码:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <meta charset="utf-8" />
    </head>
    <body>
        <h1>Hello World!</h1>
    
        <button onclick="ext()">external</button>
        
        <script>    
            
            var f = function (msg) {
                //if()
                alert(Object.prototype.toString.call(msg));
            }
            //调用winform 中的方法
            function ext() {
                //调用winform 中的方法
                window.external.WinF("hello");
            }
        
        </script>
    
    
    </body>
    </html>
  • 相关阅读:
    输入框input只能输入数字和小数点
    ES6判断数组是否存在重复元素
    AutoPostBack的含义
    首次的boe with wss
    我的msn能在w2k3上使用了哈哈
    挑战excel
    wss的webpart的3种开发方式
    我来操作dts olap
    My dbconn of ASP
    sharepoint学习理解过程
  • 原文地址:https://www.cnblogs.com/yougmi/p/8656281.html
Copyright © 2011-2022 走看看