zoukankan      html  css  js  c++  java
  • 在WebBrowser控件使用js调用C#方法

    有时我们需要在WebBrowser控件中嵌入了网页,然后通过html页面调用后台方法,如何实现呢?其实很简单,主要有三步:

    1. 在被调用方法所属的类上加上[ComVisible(true)]标签,意思就是当前类可以以com组件的形式供外部调用。
    2. 在WebBrowser控件中设置可被html页面调用的类即:webBrowser1.ObjectForScripting = this前端即可通过window.external访问this对象
    3. html页面调用后台方法:window.external.方法名()。此处的window.external相当于webBrowser1.ObjectForScripting

    示例代码:

    一、后台

    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    namespace jsInWebBrowserCallCSharpMethod
    {
        [ComVisible(true)] //1、必须设置且为true,否则设置webBrowser1.ObjectForScripting对象时会报错
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
                webBrowser1.Url =new Uri( Application.StartupPath + "\htmls\test.html");
                webBrowser1.ObjectForScripting = this;//2、设置js中window.external对象代表的类
            }
    
            /// <summary>
            /// 供webBrowser页面中js调用的方法
            /// </summary>
            /// <param name="msg"></param>
    /// <param name="msg2"></param>
    public void ShowMessage(string msg, string msg2) { MessageBox.Show(msg + " " + msg2); } } }

    二、test.html文件

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>测试调用winform后台方法页面</title>
        <script type="text/javascript">
            window.onload = function () {
                var btn = document.getElementById('btnCallCSharpMethod');
                btn.onclick = function () {
                    //此处window.external相当于winform中设置的webBrowser.ObjectForScripting对象
                    window.external.ShowMessage('成功调用winform类中的方法!','成功调用winform类中的方法2!');
                }
            }
        </script>
    </head>
    <body style='text-align:center;'>
        <input type='button' id='btnCallCSharpMethod' value='调用winform类中的方法' />
    </body>
    </html>

    三、运行效果

    本文转载自:http://blog.csdn.net/taoerchun/article/details/49782739

  • 相关阅读:
    django静态资源转移
    QT5 内置Multimedia开发音乐播放器
    Qt Creator 设置编码格式为 UTF-8
    QT 出错 moc_mainwindow.obj:-1: error: LNK2019: 无法解析的外部符号 " 中被引用...
    linux 安装node, 添加软链接,更改npm安装源
    django.template.exceptions.TemplateDoesNotExist: index.html
    centos下使用virtualenv建立python虚拟环境
    win7上 nginx 出现 403 Forbidden
    django安装xadmin中出现的报错汇总
    centos安装mysql57
  • 原文地址:https://www.cnblogs.com/wangwust/p/6565859.html
Copyright © 2011-2022 走看看