问题
I tried to print formatted HTML using WebBrowser class. After the print, I want to close the application. If I tried to use close the application the printing is not working. I tried using the timer also nothing works.
Please find the code below.
static void Main(string[] args) {
var b = new Program();
string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
b.runBrowserThread("file://" + appPath + "/receipt.html");
}
private void runBrowserThread(string url) {
var th = new Thread(() => {
var br = new WebBrowser();
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate(url);
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
var br = sender as WebBrowser;
br.Print();
//Application.ExitThread();
Environment.Exit(0);
}
回答1:
PrintTemplateTeardown is what you are looking for.
You can add a reference to SHDocVw
. Then you have access to interfaces like IWebBrowser2
and DWebBrowserEvents2_Event
.
You can find SHDocVw
as "Microsoft Internet Controls" in COM tab of Reference manager window.
You can subscribe DocumentCompleted
event to know when the file/url load completed. You can print html document without showing print dialog by calling IWebBrowser2.ExecWB
. Also you can subscribe to DWebBrowserEvents2_Event.PrintTemplateTeardown
to find out when print completed so you can close the application:
using System;
using System.Windows.Forms;
using SHDocVw;
class Program
{
static System.Windows.Forms.WebBrowser browser;
[STAThread]
static void Main()
{
var fileName = "http://google.com";
browser = new System.Windows.Forms.WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate(fileName);
Application.Run();
}
private static void browser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var iwb2 = (IWebBrowser2)browser.ActiveXInstance;
var events = (DWebBrowserEvents2_Event)browser.ActiveXInstance;
events.PrintTemplateTeardown += browser_PrintTemplateTeardown;
var missing = Type.Missing;
iwb2.ExecWB(OLECMDID.OLECMDID_PRINT, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
ref missing, ref missing);
}
private static void browser_PrintTemplateTeardown(object pDisp)
{
browser.Dispose();
Application.Exit();
}
}
来源:https://stackoverflow.com/questions/57310536/close-application-after-webbrowser-print