2017-10-10 85 views
0

我在浏览器控件中加载了一个HTML页面。 HTML有一个javascript函数windows.print,它试图从我的浏览器打印。请如何传递windows.print()函数以通过Winforms C#打印。或者我怎样才能传递我想打印到C#中的JavaScript对象来打印。C#winforms使用Javascript的网页浏览器控件

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

回答

0

你也许可以做这样的事情

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>"; 
     } 
    } 
} 
+0

太感谢了,那工作。现在我试图向MethodCallFromScript方法添加一个参数,但它会引发错误。它只需要一个论据。 –

+0

你总是可以定义一个方法来获取ScriptManager类的多个参数,定义一个适合你的js函数调用的方法签名并调用它。 – Charles

+0

请你举个例子,说明如何用上面的代码实现这个功能? –

相关问题