PrintDialog In C#

A PrintDialog control is used to open the Windows Print Dialog and let the user select the printer, set printer and paper properties, and print a file. A typical Open File Dialog looks like Figure 1 where you select a printer from available printers, set printer properties, set print range, number of pages and copies and so on. Clicking on the OK button sends the document to the printer. 

PrintDialog In C#
Figure 1

Creating a PrintDialog

We can create a PrintDialog at design-time as well as at run-time.

Design-time

To create a PrintDialog control at design-time, you simply drag and drop a PrintDialog control from Toolbox to a Form in Visual Studio. After you drag and drop a PrintDialog on a Form, the PrintDialog looks like Figure 2.

PrintDialog In C#
Figure 2

Run-time

Creating a PrintDialog control at run-time is simple. The first step is to create an instance of PrintDialog class and then call the ShowDialog method. The following code snippet creates a PrintDialog control.

  1. PrintDialog PrintDialog1 = newPrintDialog();  
  2. PrintDialog1.ShowDialog();  

Printing Documents

PrintDocument object represents a document to be printed. Once a PrintDocument is created, we can set the Document property of PrintDialog as this document. After that we can also set other properties.The following code snippet creates a PrintDialog and sends some text to a printer.

  1. privatevoid PrintButton_Click(object sender, EventArgs e) {  
  2.     PrintDialog printDlg = newPrintDialog();  
  3.     PrintDocument printDoc = newPrintDocument();  
  4.     printDoc.DocumentName = "Print Document";  
  5.     printDlg.Document = printDoc;  
  6.     printDlg.AllowSelection = true;  
  7.     printDlg.AllowSomePages = true;  
  8.     //Call ShowDialog  
  9.     if (printDlg.ShowDialog() == DialogResult.OK) printDoc.Print();  
  10. }  

More Readings

I do not want to duplicate the work but here are various articles on printing.

Summary

A PrintDialog control allows users to launch Windows Open File Dialog and select files. In this article, we discussed how to use a Windows Open File Dialog and set its properties in a Windows Forms application.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.