Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Choose the Printers Attached to a User's Computer in Windows Forms

Often, users want to choose a printer other than the default printer to print to. You can enable users to choose a printer from among those currently installed by using the PrintDialog component. Through the PrintDialog component, the DialogResult of the PrintDialog component is captured and used to select the printer.

In the following procedure, a text file is selected to be printed to the default printer. The PrintDialog class is then instantiated.

To choose a printer and then print a file

  • Select the printer to be used using the PrintDialogcomponent.

    In the following code example, there are two events being handled. In the first, a Button control's Click event, the PrintDialogclass is instantiated and the printer selected by the user is captured in the DialogResultproperty.

    In the second event, the PrintPage event of the PrintDocumentcomponent, a sample document is printed to the printer specified.

    private void button1_Click(object sender, System.EventArgs e)
    {
       PrintDialog printDialog1 = new PrintDialog();
       printDialog1.Document = printDocument1;
       DialogResult result = printDialog1.ShowDialog();
       if (result == DialogResult.OK)
       {
          printDocument1.Print();
       }
    }
    
    private void printDocument1_PrintPage(object sender, 
    System.Drawing.Printing.PrintPageEventArgs e)
    {
       e.Graphics.FillRectangle(Brushes.Red, 
         new Rectangle(500, 500, 500, 500));
    }
    

    (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler.

    this.printDocument1.PrintPage += new
       System.Drawing.Printing.PrintPageEventHandler
       (this.printDocument1_PrintPage);
    this.button1.Click += new System.EventHandler(this.button1_Click);
    
Show:
© 2015 Microsoft