Windows common dialogs - PrintPreviewDialog
Explains how to integrate the windows common task "print preview dialog box" in our application.
The PrintDialog control is used to display the dialog box for printing options. Let us see how we can use implement this dialog box:
- Open the project. First, drag the PrintDocument control from the Printing section of the Toolbox and drop it on the form. The control will be displayed in the control tray with its default name - printDocument1. This is an instance of the PrintDocument class and is required for all printing related tasks.
- Next, drag and drop the PrintDialog control on the form. The control will be added to the control tray. Select the control and set its Document property to printDocument1 using the drop down list in the properties window.
- Switch to the code view and add the following statement at the top (just below the other namespaces):
using System.Drawing.Printing;
We have added this namespace to use the printing related classes.
Next, define a method named PrintDoc() as shown here:
void PrintDoc() { try {
if (printDialog1.ShowDialog() == DialogResult.OK) { printDocument1.Print(); } } catch (InvalidPrinterException ex) { MessageBox.Show(ex.Message); } }
Inside the try block, the ShowDialog() will display the printing dialog box. After selecting the required options in the dialog box, if the user clicks the OK button, the Print() method of the printDocument1 will be called to print the document. However, in case of any exception (error), the program will enter the catch block and display appropriate error message generated by the InvalidPrinterException class.
- We can now call the PrintDoc() method from the click event of the related menu option and toolbar button:
private void mnuFilePrint_Click(object sender, EventArgs e) { PrintDoc(); }