• 在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

  • 相关阅读:
    nodejs dateformat date-utils
    nodejs async
    nodejs dateformat date-utils
    nodejs timer block-timer timer-ease
    linux 修改 ssh 的端口号,启动hg服务
    linux 下添加 路由
    tkprof 命令行工具用法
    通过API删除库存货位
    使用FROM个性化修改标准FORM的LOV
    批量更新 ITEM 物料属性
  • 原文地址:https://www.cnblogs.com/wangwust/p/6565859.html
Copyright © 2020-2023  润新知