zoukankan      html  css  js  c++  java
  • C#和网页js互调代码

    C#和网页js互调代码

    1、先写个网页放在主程序目录下:test.html

    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>测试网页</title>
        <script>
            function MyFunc(num) {
                alert("大家好,这是js代码中的Alert,我将返回30!");
                return 30 + num;
            }
        </script>
    </head>
    <body>
        <input type="button" onclick="window.external.MyMessageBox('javascript访问C#代码');" value="点击测试调用C#中的方法!" />
    </body>
    </html>

    2、打开WinForm,拖个按钮,拖个WebBrowser。

    3、写C#代码并测试

    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;
    
    namespace WebWithForm
    {
        [System.Runtime.InteropServices.ComVisible(true)]
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.webBrowser2.ObjectForScripting = this;
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                this.webBrowser2.Navigate(Application.StartupPath + "\test.html");
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var result = this.webBrowser2.Document.InvokeScript("MyFunc", new object[] { 30 });
                this.Text = this.webBrowser2.Version.ToString();
                label1.Text = "网页返回:" + result;
            }
    
            public void MyMessageBox(string message)
            {
                MessageBox.Show("这是C#的MessageBox提示:" + message);
            }
    
        }
    }

    4、运行效果:

  • 相关阅读:
    new和malloc的区别
    C++中的数据类型强制转换方法
    C++中pair和make_pair的区别
    PlantUML 图绘制类库--VSCODE插件
    Exception: HOUR_OF_DAY: 0 -> 1的问题
    Fiddler手机抓包工具如何设置过滤域名
    MySQL 正则表达式 REGEXP
    ASP.NET Web API 2 中的属性路由
    windows服务搭建(VS2019创建Windows服务不显示安装组件)
    JWT的验证(转载)
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/5038593.html
Copyright © 2011-2022 走看看