0
我在瀏覽器控件中加載了一個HTML頁面。 HTML有一個javascript函數windows.print,它試圖從我的瀏覽器打印。請如何傳遞windows.print()函數以通過Winforms C#打印。或者我怎樣才能傳遞我想打印到C#中的JavaScript對象來打印。C#winforms使用Javascript的網頁瀏覽器控件
請問我是C#初學者,希望能有詳細的解釋。非常感謝!
我在瀏覽器控件中加載了一個HTML頁面。 HTML有一個javascript函數windows.print,它試圖從我的瀏覽器打印。請如何傳遞windows.print()函數以通過Winforms C#打印。或者我怎樣才能傳遞我想打印到C#中的JavaScript對象來打印。C#winforms使用Javascript的網頁瀏覽器控件
請問我是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>";
}
}
}
太感謝了,那工作。現在我試圖向MethodCallFromScript方法添加一個參數,但它會引發錯誤。它只需要一個論據。 –
你總是可以定義一個方法來獲取ScriptManager類的多個參數,定義一個適合你的js函數調用的方法簽名並調用它。 – Charles
請你舉個例子,說明如何用上面的代碼實現這個功能? –