zoukankan      html  css  js  c++  java
  • C# webBrowser(wpf/winform) 互调js

    1.winform

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [ComVisible(true)]
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    this.Load += Form1_Load;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    webBrowser1.ObjectForScripting = this;//具体公开的对象,这里可以公开自定义对象
    webBrowser1.Navigate(Application.StartupPath + "/dom.html");
    }

    private void button1_Click(object sender, EventArgs e)
    {
    webBrowser1.Document.InvokeScript("Run", new object[] { "test" });
    }

    public void ShowMsg(string msg)
    {
    MessageBox.Show(msg);
    }

    }

    2.wpf


    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
    this.webBrowser1.ObjectForScripting = new OprateBasic();
    Uri uri = new Uri(@"pack://application:,,,/dom.html");
    Stream source = Application.GetResourceStream(uri).Stream;
    webBrowser1.NavigateToStream(source);
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
    webBrowser1.InvokeScript("Run", new object[] { "test" });
    }
    }

    [ComVisible(true)] // 将该类设置为com可访问
    public class OprateBasic
    {
    public void ShowMsg(string msg)
    {
    MessageBox.Show(msg);
    }
    }

    dom.html

    <!DOCTYPE html>

    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta charset="utf-8" />
    <title></title>
    </head>
    <body>
    <script type="text/javascript" charset="utf-8">
    function Run(str) {

    window.external.ShowMsg(str);
    }
    </script>
    </body>
    </html>

  • 相关阅读:
    预备作业02:体会做中学(Learning By Doing)
    寒假作业01
    20210418第 237 场周赛(一)
    机器学习第七堂课20210415
    云计算与信息安全第七节课20210413
    操作系统第七堂课2021年0412内存管理基础
    机器学习第六堂课20210408
    云计算与信息安全第六节课20210406
    机器学习第五节课20210401
    云计算与信息安全第五堂课20210330
  • 原文地址:https://www.cnblogs.com/Logan626/p/5333328.html
Copyright © 2011-2022 走看看