1

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?

Community
  • 1
  • 1
Nico
  • 11
  • 1
  • 4
  • 1
    You need to handle `PrintTemplateTeardown` event. Example: http://stackoverflow.com/a/19737374/1768303 – noseratio Mar 25 '14 at 11:48
  • I have my **PrintDone** for the **PrintTemplateTeardown** event, the problem is I dont want to do the print in **Shown**, think it's make some problems – Nico Mar 25 '14 at 12:19
  • The sample I linked doesn't have a visible `WebBrowser` at all. It's a console app. – noseratio Mar 25 '14 at 22:45
  • OK, I will try with this one, thank you very much – Nico Mar 26 '14 at 08:26

0 Answers0