开发者

Print on a background thread

开发者 https://www.devze.com 2022-12-26 17:45 出处:网络
开发者_运维技巧I want to print a html page from c# application but on a back ground thread because if Iprint the doc on main thread UI freezes for few seconds and I dont want that.
开发者_运维技巧

I want to print a html page from c# application but on a back ground thread because if I print the doc on main thread UI freezes for few seconds and I dont want that.

I have tried WebBrowser control but it need to be hosted on some form to get it work. Hosting this control is still acceptable but Print method needs to be called from same thread the control was created on. I tried calling Print method of WebBrowser from other thread but it neither work nor it give any error/exception. I have also tried InternetExplorerClass but it start iexplorer.exe and takes too much time.

Is there any other way in which I can print html page on a diffrent (non UI) thread?


I'd use a backgroundworker for this purpose - since you've already got a winform and everthing. Drag a background worker and a webbrowser to your form and you can use the following code (UI freezes for milliseconds when the print is actually spooled); I've used a test button (2) for the call;

using System.Threading;

    private void button2_Click(object sender, EventArgs e)
    {
        if (!this.backgroundWorker1.IsBusy)
        {
            this.backgroundWorker1.RunWorkerAsync("http://www.stackoverflow.com/");
        }
        else
        {
            MessageBox.Show("Already working on that piece of paper!");
        }
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        this.webBrowser1.Navigate((string)e.Argument);
        //-- only when you need to read very bulky pages: Thread.Sleep(1000);
        e.Result = true;
    }
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        this.webBrowser1.Print();
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }


Does something like this not work?

webBrowser1.BeginInvoke((MethodInvoker)delegate{webBrowser1.Print();});

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号