webbrowser中,JS调用C#代码

 

using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.ObjectForScripting = new ScriptManager();
            webBrowser1.DocumentText = @"<html>
                <head> <title>Test</title>                   
                </head>
                <body>
                <input type=""button"" value=""点击"" onclick=""window.external.CallFromJS('TEST');"" />
                </body>
                </html>";
        }

        //此类必须对 COM 可见,才能从Javascript中调用。
        [ComVisible(true)]
        public class ScriptManager
        {
            //public ScriptManager(){}

            //此方法可在JS中调用
            public void CallFromJS(string message)
            {
                MessageBox.Show(message);
            }
        }
    }
}

 

posted @ 2022-11-17 14:15  水墨晨诗  阅读(102)  评论(0编辑  收藏  举报