Javascript 的 C# winforms webbrowser 控件

C# winforms webbrowser control with Javascript

我在网络浏览器控件中加载了一个 HTML 页面。 HTML 有一个 javascript 函数 windows.print 试图从我的浏览器打印。请问如何通过 Winforms C# 传递 windows.print() 函数进行打印。或者如何将要打印的 javascript 对象传递到要打印的 C# 中。

请我是C#的初学者,希望能有详细的解释。非常感谢!

你或许可以这样做

namespace WindowsFormsApplication
{
    // This first namespace is required for the ComVisible attribute used on the ScriptManager class.
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    // This is your form.
    public partial class Form1 : Form
    {
        // This nested class must be ComVisible for the JavaScript to be able to call it.
        [ComVisible(true)]
        public class ScriptManager
        {
            // Variable to store the form of type Form1.
            private Form1 mForm;

            // Constructor.
            public ScriptManager(Form1 form)
            {
                // Save the form so it can be referenced later.
                mForm = form;
            }

            // This method can be called from JavaScript.
            public void MethodToCallFromScript()
            {
                // Call a method on the form.
                mForm.DoSomething();
            }

            // This method can also be called from JavaScript.
            public void AnotherMethod(string message)
            {
                MessageBox.Show(message);
            }
        }

        // This method will be called by the other method (MethodToCallFromScript) that gets called by JavaScript.
        public void DoSomething()
        {
            // Indicate success.
            MessageBox.Show("It worked!");
        }

        // Constructor.
        public Form1()
        {
            // Boilerplate code.
            InitializeComponent();

            // Set the WebBrowser to use an instance of the ScriptManager to handle method calls to C#.
            webBrowser1.ObjectForScripting = new ScriptManager(this);

            // Create the webpage.
            webBrowser1.DocumentText = @"<html>
                <head>
                    <title>Test</title>
                </head>
                <body>
                <input type=""button"" value=""Go!"" onclick=""window.external.MethodToCallFromScript();"" />
                    <br />
                    <input type=""button"" value=""Go Again!"" onclick=""window.external.AnotherMethod('Hello');"" />
                </body>
                </html>";
        }
    }
}