WebBrowser, wait until finished printing

一个人想着一个人 提交于 2021-01-29 03:11:49

问题


I'm working with the WebBrowser control in C#. I use the WebBrowser in a form and I insert some HTML and CSS into this WebBrowser. It works well.

I would like to print from this WebBrowser directly and check the print status. If it finishes, the application will close automatically. I searched for something like: WebBrowser.Print() wait until complete. .NET.

It works, but when I'm in debug mode, my code never goes through the event "DocumentCompleted". So I tried printing in form's Shown event. Here is the code:

using System.Reflection;
using System.Threading;
using SHDocVw;

private void PrintFacture_Load(object sender, EventArgs e)
{
    string content = "Some HTML+CSS";
    webBrowser1.Navigate("about:blank");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
    webBrowser1.Document.Write(content);
}

private void PrintFacture_Shown(object sender, EventArgs e)
{
    string keyName = @"Software\Microsoft\Internet Explorer\PageSetup";
    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
    {
        if (key != null)
        {
            string old_footer = key.GetValue("footer").ToString();
            string old_header = key.GetValue("header").ToString();
            key.SetValue("footer", "");
            key.SetValue("header", "");

            var wbax = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
            wbax.PrintTemplateTeardown += new DWebBrowserEvents2_PrintTemplateTeardownEventHandler(PrintDone);  
            webBrowser1.Print();

            key.SetValue("footer", old_footer);
            key.SetValue("header", old_header);
        }
    }
}

private void PrintDone(object sender)
{
    var wbax = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
    wbax.PrintTemplateTeardown -= new DWebBrowserEvents2_PrintTemplateTeardownEventHandler(PrintDone);
    Application.Exit();
}

My question is why my code never received the WebBrowser event "DocumentCompleted"?

Is there some better solutions to do this? I think printing in form's Shown event is not the best idea. Any good ideas?

来源:https://stackoverflow.com/questions/22633471/webbrowser-wait-until-finished-printing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!