Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUI Locking up when using PrintDialog and PrintPreviewDialog in .net

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();
like image 760
EMaddox84 Avatar asked Dec 05 '08 00:12

EMaddox84


1 Answers

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.

like image 53
Matthew Savage Avatar answered Sep 19 '22 11:09

Matthew Savage