Reputation: 245
I'm using .net's PrintPreviewDialog and whenever it's generating a preview, it locks up my GUI in the background and makes it look like it has crashed until the preview is finished. Seeing how the .net's page progress window that pops up isn't a dialog, the back ground can be selected which then comes to the front in a half drawn, locked up manner. This also happens when the user clicks the actual "Print" button on the preview dialog, and when I just run PrintDocument.Print(). Is there an easy way to modify the following code to stop the GUI from hanging when the user is waiting for .net to draw the print pages:
//just showing a preview, hangs up background GUI on generating the preview
// and when user prints straight from the preview
this.printPreviewDialog.ShowDialog(this);
//just trying to print a .net PrintDocument class, GUI hangs in background
// when .net is drawing the pages
this.printDocument.Print();
Upvotes: 6
Views: 4517
Reputation: 3809
Dot Net Rocks TV (dnrtv) covers how to run things in a background thread to keep the GUI thread free in episode 16.
Upvotes: 0
Reputation: 3814
Another option would be spinning up a new UI thread:
ThreadStart ts = () =>
{
printDocument.Print();
// Start the message loop to prevent the thread from finishing straight away.
System.Windows.Forms.Application.Run();
};
Thread t = new Thread(ts);
t.SetApartmentState(ApartmentState.STA);
t.Start();
Keep in mind this code isn't tested and may need some tuning (especially the message loop part) - and you might also want to keep in mind you will need to shut down the thread at some time - so perhaps you might want a class to handle the interaction and lifetime management.
Upvotes: 3
Reputation: 1342
the ShowDialog method creates a modal window, it blocks the main thread. the Show method creates a nonmodal window, it doesn't block the main thread.
When you call
this.printDocument.Print();
it again does its work in the main thread.
To do that in a background thread, you could try something like (off the top of my head)
ThreadPool.QueueUserWorkItem ( (obj) => this.printDocument.Print() );
it uses a new thread to print the document, instead of the main GUI thread.
If you want to know more, you have to research threading
Upvotes: 2
Reputation: 12656
You should probably call those methods in a different thread if they take so long. Investigate the use of BackgroundWorker to help you.
Also, It could be that it's because of the windows printers and not your code (are you using a network printer? if so, change to a virtual printer and see if that changes anything).
Upvotes: 1