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

Creating Standard Windows Forms Print Jobs

Visual Studio .NET 2003

The foundation of printing in Windows Forms is the PrintDocument component — more specifically, the PrintPage event. By writing code to handle this event, you can specify what to print and how to print it.

To create a print job

  1. Add a PrintDocument component to your form.
  2. Right-click your form and choose View Code.
  3. Write code to handle the PrintPage event.

    You will have to code your own printing logic. Additionally, you will have to specify the material to be printed.

    In the example below, a sample graphic (a red rectangle) is created in the PrintPage event handler to act as material to be printed.

    ' Visual Basic
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
       e.Graphics.FillRectangle(Brushes.Red, New Rectangle(500, 500, 500, 500))
    End Sub
    
    // C#
    private void printDocument1_PrintPage(object sender, 
    System.Drawing.Printing.PrintPageEventArgs e)
    {
       e.Graphics.FillRectangle(Brushes.Red, 
         new Rectangle(500, 500, 500, 500));
    }
    
    // C++
    private:
       System::Void printDocument1_PrintPage(System::Object *  sender,
          System::Drawing::Printing::PrintPageEventArgs *  e)
       {
          e->Graphics->FillRectangle(Brushes::Red,
             Rectangle(500, 500, 500, 500));
       }
    
    Visual C# and Visual C++ Note   Be sure that the necessary code to enable the event handler is present. In this case, it would be similar to the following:
    // C#
    this.printDocument1.PrintPage += new
    System.Drawing.Printing.PrintPageEventHandler
    (this.printDocument1_PrintPage);
    // C++
    printDocument1->PrintPage += new
    System::Drawing::Printing::PrintPageEventHandler
    (this, printDocument1_PrintPage);

    You may also want to write code for the BeginPrint and EndPrint events, perhaps including an integer representing the total number of pages to print that is decremented as each page prints.

    Note   You can add a PrintDialog component to your form to provide a clean and efficient user interface to your users. Setting the Document property of the PrintDialog component allows you to set properties related to the print document you are working with on your form. For more information about the PrintDialog component, see PrintDialog Component.

For more information on the specifics of Windows Forms print jobs, including how to create a print job programmatically, see PrintPageEventArgs Class.

See Also

PrintDocument Component | Windows Forms Print Support | Windows Forms

Show:
© 2015 Microsoft