0

I am using WinForms WebBrowser to print the content of it in my application. But the point is that I want the printing be done in other thread, as it might be long, and i am getting threading error (: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment). Here is the code:

printing.frmPrinting frm = new printing.frmPrinting();
Thread tprint = new Thread(delegate() { frm.PrintHelpPage(_htmlcontent); });
tprint.Start();

The printer function:

public void PrintHelpPage(string _content)
    {
        // Create a WebBrowser instance. 
        WebBrowser webBrowserForPrinting = new WebBrowser();

        // Add an event handler that prints the document after it loads.
        webBrowserForPrinting.DocumentCompleted +=
            new WebBrowserDocumentCompletedEventHandler(PrintDocument);

        // Set the Url property to load the document.
        webBrowserForPrinting.DocumentText = _content;
    }

    private void PrintDocument(object sender,
        WebBrowserDocumentCompletedEventArgs e)
    {

        ClearBrowserPrintHeaderAndFooter();
        // Print the document now that it is fully loaded.
        ((WebBrowser)sender).Print();
        // Dispose the WebBrowser now that the task is complete. 
        ((WebBrowser)sender).Dispose();
    }
v.chjen
  • 615
  • 1
  • 8
  • 20
  • http://stackoverflow.com/questions/1418466/single-threaded-apartment-cannot-instantiate-activex-control, this link will be helpful. – Hassan Apr 18 '14 at 09:31
  • @HassanNisar thx, the run-time error does not appear, but now the function does not print anything. – v.chjen Apr 18 '14 at 09:40
  • Show the changes you have done to avoid STA error – Hassan Apr 18 '14 at 09:44
  • 1
    Yeah, that link isn't that helpful. Another thing you **have** to do in an STA is run a message loop. The DocumentCompleted event will not fire if you don't. Try [this one instead](http://stackoverflow.com/a/21684059/17034). – Hans Passant Apr 18 '14 at 10:26

0 Answers0