Home

Printing

 

The Print Dialog Box

 

Introduction

Besides saving or opening files, another operation users perform on a document consists of printing it. Printing is the ability to render, on paper, the result of a control's content or the contents of various controls. This is performed using an external device called a printer peripheral or simply a printer. To do this, users need access to a printer device.

There are two main ways users print a document. They can ask the application they are using to send the document directly to a printer or they can use a dialog box to decide how the printing should be done.

Practical LearningPractical Learning: Introducing Printing

  1. To start a new application, on the main menu, click File -> New -> Project...
  2. In the middle list, click Windows Application and change the Name to SimpleInterest2
  3. Click OK
  4. From the Menus & Toolbars section of the Toolbox, click MenuStrip and click the form
  5. While the menu strip is still selected, in the Properties window, click (Name) and type mnuMain
  6. Under the Properties window, click Insert Standard Items
  7. On the form, click Edit and press Delete
  8. Click Tools and press Delete
  9. Click Help and press Delete
  10. Design the form as follows:
     
    Interest Rate
    Control Text Name TextAlign
    Label Label Prepared by:    
    TextBox TextBox   txtEmployeeName  
    Label Label Prepared for:    
    TextBox TextBox   txtCustomerName  
    GroupBox GroupBox Loan Preparation    
    Label Label Principal    
    TextBox TextBox 0.00 txtPrincipal Right
    Label Label Interest Rate:    
    TextBox TextBox 0.00 txtInterestRate Right
    Label Label %    
    Label Label Periods:    
    TextBox TextBox 1 txtPeriods Right
    Label Label Months    
    Button Button Calculate btnCalculate  
    GroupBox GroupBox Results    
    Label Label Interest Earned:    
    TextBox TextBox 0.00 txtInterestEarned Right
    Label Label Future Value    
    TextBox TextBox 0.00 txtFutureValue Right

  11. On the form, double-click the Calculate button and implement its Click event as follows:
    System::Void btnCalculate_Click(System::Object^ sender, System::EventArgs^ e)
    {
            double Principal    = 0.00,
                        InterestRate = 0.00,
                        InterestEarned,
                        FutureValue;
            double Periods = 0.00;
    
            try
            {
                    Principal = double::Parse(txtPrincipal->Text);
            }
            catch(FormatException ^)
            {
                    MessageBox::Show("The value you entered for the "
                                    "principal is not valid");
            }
    
            try
            {
                    InterestRate = double::Parse(txtInterestRate->Text);
            }
            catch(FormatException ^)
            {
                    MessageBox::Show("Wrong Value: The interest rate must "
                                    "be a value between 0 and 100");
            }
    
            try
            {
                    Periods = double::Parse(txtPeriods->Text);
            }
            catch(FormatException ^)
            {
                   MessageBox::Show("You entered an invalid value for the periods");
            }
    
            double I = InterestRate / 100;
            double p = Periods / 12;
            InterestEarned = Principal * I  * p;
            FutureValue    = Principal + InterestEarned;
    
            txtInterestEarned->Text = InterestEarned.ToString("F");
            txtFutureValue->Text = FutureValue.ToString("F");
    }
  12. Return to the form
  13. On the form, click File and double-click New
  14. Implement its Click event as follows:
    System::Void newToolStripMenuItem_Click(System::Object^ sender,
    		  			System::EventArgs^ e)
    {
        txtEmployeeName->Text = "";
        txtCustomerName->Text = "";
        txtPrincipal->Text = "0.00";
        txtInterestRate->Text = "0.00";
        txtPeriods->Text = "0";
        txtInterestEarned->Text = "0.00";
        txtFutureValue->Text = "0.00";
    }
  15. Return to the form
  16. From the Dialogs section of the Toolbox, click OpenFileDialog and click the form
  17. Change its properties as follows:
    Title: Open Existing Loan Evaluation
    DefaultExt: wal
    Filter: Watts A Loan (*.wal)|*.wal|All Files|
    Name: dlgOpen
  18. From the Dialogs section of the Toolbox, click SaveFileDialog and click the form
  19. Change its properties as follows:
    Title: Save Loan Evaluation
    DefaultExt: wal
    Filter: Watts A Loan (*.wal)|*.wal|All Files|
    Name: dlgSave
  20. On the form, click File and double-click Open
  21. In the top section of the file, type the following:
    #pragma once
    
    namespace SimpleInterest2 {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    	using namespace System::IO;
  22. Scroll down and implement its Click event as follows:
    System::Void openToolStripMenuItem_Click(System::Object^  sender,
    		  			 System::EventArgs^  e)
    {
        dlgOpen->InitialDirectory = "C:\\Watts A Loan";
    
        if( dlgOpen->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            FileStream ^ fleWattsALoan = gcnew FileStream(dlgOpen->FileName,
                   					      FileMode::Open,
                   					      FileAccess::Read,
                   					      FileShare::Read);
            BinaryReader ^ bnrWattsALoan = gcnew BinaryReader(fleWattsALoan);
    
            txtEmployeeName->Text   = bnrWattsALoan->ReadString();
            txtCustomerName->Text   = bnrWattsALoan->ReadString();
            txtPrincipal->Text      = bnrWattsALoan->ReadString();
            txtInterestRate->Text   = bnrWattsALoan->ReadString();
            txtPeriods->Text        = bnrWattsALoan->ReadString();
            txtInterestEarned->Text = bnrWattsALoan->ReadString();
            txtFutureValue->Text    = bnrWattsALoan->ReadString();
    
            bnrWattsALoan->Close();
            fleWattsALoan->Close();
        }
    }
  23. Return to the form
  24. On the form, click File and double-click Save
  25. Implement the event as follows:
    System::Void saveToolStripMenuItem_Click(System::Object^  sender, 
    		  			 System::EventArgs^  e)
    {
        // Just in case, calculate the order now
        btnCalculate_Click(sender, e);
    
        // Display the Save dialog box and find out if the user clicked OK
        if( dlgSave->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            // Create a new file using the name of the Save dialog box
            FileStream ^ fleWattsALoan = gcnew FileStream(dlgSave->FileName,
                       				      FileMode::Create,
                       				      FileAccess::Write,
                       				      FileShare::Write);
            BinaryWriter ^ bnrWattsALoan = gcnew BinaryWriter(fleWattsALoan);
    
            // Write each value in the file
            bnrWattsALoan->Write(txtEmployeeName->Text);
            bnrWattsALoan->Write(txtCustomerName->Text);
            bnrWattsALoan->Write(txtPrincipal->Text);
            bnrWattsALoan->Write(txtInterestRate->Text);
            bnrWattsALoan->Write(txtPeriods->Text);
            bnrWattsALoan->Write(txtInterestEarned->Text);
            bnrWattsALoan->Write(txtFutureValue->Text);
    
            bnrWattsALoan->Close();
            fleWattsALoan->Close();
    
            newToolStripMenuItem_Click(sender, e);
        }
    }
  26. To execute the application, press F5
  27. Create a new record. Here is an example:
     
    Watts A Loan
  28. On the main menu of the form, click File -> Save
  29. Set the file name to ep
  30. Click Save
  31. Create another loan and calculate it
     
    Watts A Loan
  32. Save it as hgm
  33. Close the form and return to your programming environment
  34. Press F5 to execute
  35. Try opening a previously saved order
  36. Close the form and return to your programming environment

Introduction to the Print Dialog Box

One of the ways users print consists of sending the document to the printer. To directly send a document to the printer, you need to make sure that the control, whose value needs to be printed, supports printing. To accommodate the users of your application, you can provide a menu item or a button they would click. An example of such a button would be Print . To print, the user can click this button. That is the case when using WordPad: its Standard toolbar is equipped with such a button. With this type of printing, when the user decides to print, the whole document would be printed "as is", in color if the document is colored and if the printer supports colors. If there is more than one printer, the computer would use what is known as the default printer.

If you want users to be able to configure or customize the printing process, Microsoft Windows provides a common dialog box called Print:

The Print dialog box allows a user to select a printer if more than one is available. The user can decide either to print the whole document, to print a range of pages, or to print a portion of the document that was previously selected. The user can also decide on the number of copies to print from the document, the range specified, or the selected portion. Furthermore, the user can access the particular characteristics of the selected printer and specify how the printer should perform the job. For example, if the selected printer can print in color and the document is in color but the user wants to print in black and white, he or she can specify this using the Properties button.

Providing a Printer

To provide the users with the ability to customize printing through the Print dialog box, you can add a PrintDialog object PrintDialog from the Toolbox to your form. The PrintDialog control is implemented through the PrintDialog class of the System::Windows::Forms namespace. To programmatically create a PrintDialog object, you can declare a pointer to PrinterDialog. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
private:
    Button ^ btnPrint;

public:
    CExercise()
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	btnPrint = gcnew Button;
	btnPrint->Location = Point(20, 20);
	btnPrint->Text = "Print";
	btnPrint->Click += gcnew EventHandler(this, &CExercise::btnPrintClick);

	Controls->Add(btnPrint);
        Text = L"Exercise";
        StartPosition = FormStartPosition::CenterScreen;
    }

    void btnPrintClick(Object ^ sender, EventArgs ^ e)
    {
	PrintDialog ^ dlgPrint = gcnew PrintDialog;
    }
};

int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    return 0;
}

To present the Print dialog box to the user, you can call its ShowDialog() member function.

Practical LearningPractical Learning: Providing a Print Dialog Box

  1. From the Printing section of the Toolbox, click the PrintDialog button PrintDialog
  2. Click the form
  3. While the print control is still selected, in the Properties window, change its Name to dlgPrint
 
 
 

The Printing Process

 

The Document to Print

In order to print, the Print dialog box must be given a document to print. This means that you must first prepare a document prior to printing. To support this, the .NET Framework provides the PrintDocument class that is defined in the System::Drawing::Printing namespace. This class is represented in the Toolbox by the PrintDocument button . Based on this, to prepare a document for printing, you can either add a PrintDocument object to your project or declare a pointer to PrintDocument. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Drawing::Printing;

public ref class CExercise : public Form
{
private:
    Button ^ btnPrint;

public:
    CExercise()
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	btnPrint = gcnew Button;
	btnPrint->Location = Point(20, 20);
	btnPrint->Text = "Print";
	btnPrint->Click += gcnew EventHandler(this, &CExercise::btnPrintClick);

	Controls->Add(btnPrint);
        Text = L"Exercise";
        StartPosition = FormStartPosition::CenterScreen;
    }

    void btnPrintClick(Object ^ sender, EventArgs ^ e)
    {
	PrintDialog ^ dlgPrint = gcnew PrintDialog;
        PrintDocument ^ docPrint = gcnew PrintDocument;
    }
};

int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    return 0;
}

After creating the document to print through a PrintDocument object, you can associate it with a PrintDialog. To support this, the PrintDialog class is equipped with the Document property. To specify the object that would carry the printing, you can assign the PrintDocument object to the PrintDialog::Document property. Here is an example:

void btnPrintClick(Object ^ sender, EventArgs ^ e)
{
    PrintDialog ^ dlgPrint = gcnew PrintDialog;
    PrintDocument ^ docPrint = gcnew PrintDocument;

    dlgPrint->Document = docPrint;
    dlgPrint->ShowDialog();
}

A document to print can be made of only one or many pages. Each page has a number of characteristics. The characteristics of a page are controlled by the PrintDocument::PageSettings property which itself is based on the PageSettings class. The PageSettings class is defined in the System::Drawing::Printing namespace. This class holds the dimensions of the page, the values of the margins applied on the page, the tray that would supply the paper (since some printers have many trays), the printer resolution, whether the page would be printed in color or black and white, whether the page would be printed in Portrait or Landscape orientation, etc. If you don't want to specify these characteristics, you can set the PrintDocument::PageSettings property to DefaultPageSettings.

If you know the name of the document to be printed, you can assign it to the PrintDocument::DocumentName property. Here is an example:

System::Void btnPrint_Click(System::Object ^  sender, System::EventArgs ^  e)
{
	 PrintDialog   ^ dlgPrint = gcnew PrintDialog;
	 PrintDocument ^ docPrint = gcnew PrintDocument;

	 docPrint->DocumentName  = L"Exercise";
	 dlgPrint->Document      = docPrint;

	 dlgPrint->ShowDialog();
}

To actually print the document, you can call the PrintDocument::Print() member function. Its syntax is:

public:
    void Print();

Practical LearningPractical Learning: Providing the Document to Print

  1. From the Printing section of the Toolbox, click the PrintDocument button PrintDocument
  2. Click the form
  3. While the print document control is still selected, in the Properties window, change its name to docPrint
  4. Under the form, click dlgPrint
  5. In the Properties window, click Document and select docPrint

Events Related to Printing

When the PrintDocument::Print() member function is called, the printing process would start by firing the BeginPrint event but this event occurs before the first page is printed. The BeginPrint event is of type PrintEventArgs which doesn't hold any particular information, especially for the BeginPrint event. This event allows you to take some early actions, if necessary, before the printer receives the job.

Once the printer is ready, the application would then need to know what needs to be printed on the paper. At this time, the PrintPage event is fired. The PrintPage event is of type PrintPageEventArgs. The PrintPageEventArgs class allows you to fully customize the page of the document to be printed. For example, it is equipped with a Graphics property that allows you to "draw" anything you want on the paper. The PrintPageEventArgs class also allows you to get the location and dimensions of the area to be printed. This is represented by the PageBounds property, which produces a Rectangle object.

Once the PrintDocument object is ready, you must pass it to the Print dialog box. To do that, assign the name of the PrintDocument variable to the PrintDialog::Document property.

Practical LearningPractical Learning: Printing a Document

  1. On the bar under the form, double-click docPrint to generate its default event
  2. Implement the PrintPage event as follows:
    System::Void docPrint_PrintPage(System::Object^  sender, System::Drawing::Printing::PrintPageEventArgs^  e)
    {
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 60, 90, 700, 90);
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 60, 93, 700, 93);
    
        String ^ strDisplay = "Watts A Loan";
        System::Drawing::Font ^ fntString = gcnew System::Drawing::Font("Times New Roman", 28,
                                                 FontStyle::Bold);
        e->Graphics->DrawString(strDisplay, fntString,
                              Brushes::Black, 280, 100);
    
        strDisplay = "Loan Evaluation";
        fntString = gcnew System::Drawing::Font("Times New Roman", 18,
                                            FontStyle::Bold);
        e->Graphics->DrawString(strDisplay, fntString,
                              Brushes::Black, 320, 150);
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 60, 184, 700, 184);
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 60, 187, 700, 187);
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 100, 250, 680, 250);
    
        fntString = gcnew System::Drawing::Font("Times New Roman", 10,
                                            FontStyle::Bold);
        e->Graphics->DrawString("Prepared by:", fntString,
                              Brushes::Black, 100, 260);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10,
                                            FontStyle::Regular);
        e->Graphics->DrawString(txtEmployeeName->Text, fntString,
                              Brushes::Black, 260, 260); ;
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 100, 280, 680, 280);
    
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Bold);
        e->Graphics->DrawString("Prepared for:", fntString,
            Brushes::Black, 100, 290);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
        e->Graphics->DrawString(txtCustomerName->Text, fntString,
            Brushes::Black, 260, 290); ;
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 100, 310, 680, 310);
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 100, 340, 680, 340);
    
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Bold);
        e->Graphics->DrawString("Principal:", fntString, Brushes::Black, 100, 350);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
    
        e->Graphics->DrawString(txtPrincipal->Text, fntString, Brushes::Black, 260, 350);
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 100, 370, 680, 370);
    
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Bold);
        e->Graphics->DrawString("Interest Rate:", fntString,
            Brushes::Black, 100, 380);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
        e->Graphics->DrawString(txtInterestRate->Text, fntString,
                              Brushes::Black,
                              RectangleF(260, 380, 420, 380));
        e->Graphics->DrawString("%", fntString, Brushes::Black, 300, 380);
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 100, 400, 680, 400);
    
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Bold);
        e->Graphics->DrawString("Periods:", fntString,
                              Brushes::Black, 100, 410);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
        e->Graphics->DrawString(txtPeriods->Text, fntString,
                              Brushes::Black,
                              RectangleF(260, 410, 400, 410));
        e->Graphics->DrawString("Months", fntString, Brushes::Black, 300, 410);
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 100, 430, 680, 430);
    
        e->Graphics->DrawString("Interest Earned:", fntString,
                              Brushes::Black, 100, 440);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
        e->Graphics->DrawString(txtInterestEarned->Text, fntString,
                              Brushes::Black,
                              RectangleF(260, 440, 420, 440));
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 1), 100, 460, 680, 460);
    
        e->Graphics->DrawString("Future Value:", fntString,
                              Brushes::Black, 100, 470);
        fntString = gcnew System::Drawing::Font("Times New Roman", 10, FontStyle::Regular);
        e->Graphics->DrawString(txtFutureValue->Text, fntString,
                              Brushes::Black,
                              RectangleF(260, 470, 420, 470));
    
        e->Graphics->DrawLine(gcnew Pen(Color::Black, 2), 100, 500, 680, 500);
    }
  3. Return to the form
  4. On the form, click File and double-click Print...
  5. Implement its Click event as follows:
    System::Void printToolStripMenuItem_Click(System::Object^  sender,
    					  System::EventArgs^  e)
    {
        if(  dlgPrint->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            docPrint->Print();
        }
    }
  6. Execute the application and open one of the previously saved orders
  7. On the main menu of the form, click File -> Print and click OK
  8. After using it, close the form and return to your programming environment

The Printer Settings

In the above example, we saw a somewhat simplistic way of making the Print dialog box available to the user. This dialog box offers many options defined as the Printer Settings. To support the various options of a Print dialog box, the PrintDialog class is equipped with a property called PrinterSettings, which itself is defined from the PrinterSettings class, which holds all possible characteristics of a printer:

public:
    property PrinterSettings^ PrinterSettings
    {
        PrinterSettings^ get ();
        void set (PrinterSettings^ value);
    }

The first option presented to the user is the name of the printer to be used. This is representated by the PrinterName property:

public:
    property String^ PrinterName {
        String^ get ();
        void set (String^ value);
    }

Because there can be many printers available to the user, the printers are presented as a combo box:

Print

The available printers may also be presented as a list view:

The Name combo box in the Printer section or the Select Printer list view allows the user to select the printer that will handle the job. If you are writing a universal application and cannot predict what printer(s) the user would have, you would not be concerned with this characteristic. If you are writing an application for a special company or you are creating a particular application and you know for sure what printer should be used to print the current document, then you can specify the printer to use. To do this, assign the (exact) name of the printer to the PrinterSettings::PrinterName property. On the other hand, if for some reason you want to know what printer the user selected to print the document, you can get the value of this PrinterName property.

Under the Name combo box, the labels provide the status of the selected printer (whether it is ready or not), the type of printer (such as its manufacturer), its location (such as where in the building the printer is located; the person who installed the printer may have provided this printer), and an optional comment (this information is created by the person who installed the printer or it can be changed in the printer's properties).

After selecting the printer, the user can access the properties of that particular printer. Different printers support different options. To configure the printed paper based on the selected printer, the user can click either Properties or Preferences. This opens the Document Properties or the Printing Preferences dialog box. The content of this dialog box (highly) depends on the printer that was selected but some characteristics are shared among printers.

On the lower-right side of the Printer section or of the Select Printer section, there is a check box labeled Print To File. When this check box is checked, the document is transformed into a file rather than being printed. In this case, if the user clicks OK, a dialog box would come up, asking the user to specify the path and a name for the new file that will be created:

Print to File

If you want the Print To File check box to be checked, set the PrinterSettings::PrintFoFile Boolean property to true. Its default value is false, which lets the user decide whether to check it or not.

After selecting the printer and deciding whether to physically print or to only create a printed file, the user can click OK. If the document is made of only one page, it would be printed. If the document contains more than one page, the user may want to print only one page, a range of pages, or all pages. The user can also select a section in the document and print only that section. This decision is made using the Page Range section. This section provides four radio buttons. The first radio button labeled All is selected by default and allows the user to print the whole document. By default, the second radio button is disabled. If the user had selected a section of the document to print, then the second radio button, labeled Selection would be enabled:

Selection

This allows the user to still specify whether to print the whole document or only the section that was selected. If the document contains more than one page, the user can navigate to a particular page and decide to print only that page using the Current Page radio button. Again, if the document contains more than one page, the user can specify a range of pages to print. All these options are usually left up to the user. On the other hand, if you want to specify the range of pages to print, you can use the PrinterSettings::FromPage property:

public:
    property int FromPage {
        int get ();
        void set (int value);
    }

The end is represented by the ToPage property:

public:
    property int ToPage {
        int get ();
        void set (int value);
    }

If you to specify the limits of ranges allowed to the user, use the MinimumPage property:

public:
    property int MinimumPage {
        int get ();
        void set (int value);
    }

The end range is represented by the MaximumPage property:

public:
    property int MaximumPage {
        int get ();
        void set (int value);
    }

On the right side of the Page Range section, a spin button allows the user to specify the number of copies to make when printing. If you want to specify this number by default, assign the desired value to the Copies property. If you or the user sets this number to a value higher than 1, then the printed papers can be collated or not. This is specified using the Collate check box. If you want to programmatically collate the pages or not, change the Boolean value of the Collate property:

public:
    property bool Collate {
        bool get ();
        void set (bool value);
    }

The Page Setup Dialog Box

 

Introduction

As opposed to directly printing a file, a user may want to perform some preliminary preparation on the document or the printer. Microsoft Windows provides another dialog box used to control printing. It is called Page Setup:

To provide a Page Setup to your application, you can use the PageSetupDialog button from the Toolbox. The PageSetupDialog control is based on the PageSetupDialog class which derives from the CommonDialog class.

ApplicationPractical Learning: Adding a Page Setup Dialog Box

  1. On the form, click File and, under Exit, click Type Here
  2. Type Pa&ge Setup...
  3. Move the Page Setup menu item up and position it above Print...
     
    Interest Rate
  4. Using the Properties window, change its (Name) to mnuFilePageSetup
  5. From the Printing section of the Toolbox, click the PageSetupDialog icon
  6. Click the form
  7. While the print document control is still selected, in the Properties window, change its Name to dlgPageSetup

Characteristics of the Page Setup Dialog Box

When using the Page Setup dialog box, the user must first select a printer. This is usually done already by the operating system that selects the default printer of the computer that called this dialog box. Otherwise, to select a printer or to change the printer, the user can click the Printer button and select or change it using the Name combo box:

Page Setup

Displaying the Page Setup Printer dialog box also allows you and/or the user to customize the printing process if necessary. If you want to do this, you can use the PageSetupDialog::PrinterSettings property which is a value of the PrinterSettings class:

public:
    property PrinterSettings^ PrinterSettings
    {
        PrinterSettings^ get ();
        void set (PrinterSettings^ value);
    }

After selecting the printer, the user can click OK. The options of the Page Setup dialog box depend on the driver of the printer selected in the Name combo box. The Page Setup dialog box allows the user to customize the appearance of the paper on which the document would be printed. On the Page Setup, the user can click the arrow of the Size combo box and select one of the configured sizes of paper. The characteristics of the paper are controlled by the PageSettings class that we mentioned earlier. For example, if the printer has many trays, as indicated by the driver of the selected printer, the user can select which tray would be used when printing. As it happens, one printer can have only one tray while another printer can have 3, 5, or more trays.

If the desired printer is on a network, the user can click the Network button to locate it. To programmatically show or hide the Network button, specify a false or true result to the PageSetupDialog::ShowNetwork Boolean property:

public:
    property bool ShowNetwork
    {
        bool get ();
        void set (bool value);
    }

The user also has the option to print the document in Portrait (vertical) or in Landscape (horizontal) position. The option to allow the user to select Portrait or Landscape is controlled by the AllowOrientation Boolean property:

public:
    property bool AllowOrientation
    {
        bool get ();
        void set (bool value);
    }

ApplicationPractical Learning: Preparing the Page Setup Dialog Box

  1. Under the form, click dlgPageSetup.
    In the Properties window, click Document and select docPrint
  2. On the form click File and double-click Page Setup
  3. Implement the event as follows:
    System::Void mnuFilePageSetup_Click(System::Object^  sender,
    				    System::EventArgs^  e)
    {
        dlgPageSetup->ShowDialog();
    }
 

Introduction to Print Preview

 

Description

If you use the printing process that solely involves the print dialog box, you may send a document to the printer without knowing what the printed document would look like on the piece of paper. In the same way, the user would have to simply accept the way you designed the printed document to appear. One way you can assist the user consists of displaying a preview of what the printed sheet would look like. This is the idea behind the concept of print preview.

Print preview consists of displaying, on the computer monitor, a sample representation of what the document would look like once printed.

Providing Print Preview

Print preview is primarily a technique of drawing a sample printed sheet on a form. It is implemented by the PrintPreviewDialog button Print Preview Dialog from the Toolbox. Therefore, at design time, to provide print preview, from the Printing section of the Toolbox and click the form. As its name indicates, the dialog box is already created but like the other dialog boxes of the .NET Framework, you must add it to a form in order to make it available in your application.

In the .NET Framework, print preview is implemented through the PrintPreviewDialog class. This class is derived from the Form class. Based on this, to programmatically create a print preview, you can start by declaring a variable of type PrintPreviewDialog. Here is an example:

using System;
using namespace System::Drawing;
using namespace System::Windows.Forms;

public class Exercise : Form
{
    Button btnPrintPreview;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnPrintPreview = gcnew Button();
        btnPrintPreview->Location = Point(12, 12);
        btnPrintPreview->Text = "&Print Preview...";
        btnPrintPreview->Width = 100;
        btnPrintPreview.Click += gcnew EventHandler(PreviewDocumentClick);

        Controls.Add(btnPrintPreview);
    }

    void PreviewDocumentClick(Object ^ sender, EventArgs ^ e)
    {
        PrintPreviewDialog dlgPrint = gcnew PrintPreviewDialog();
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

As a dialog-based object, to display the print preview, the PrintPreviewDialog class inherits the ShowDialog() member function from its parent the Form class. Here is an example:

void PreviewDocumentClick(Object ^ sender, EventArgs ^ e)
{
        PrintPreviewDialog dlgPrintPreview = gcnew PrintPreviewDialog();

        dlgPrintPreview.ShowDialog();
}

This would produce:

Print Preview

ApplicationPractical Learning: Adding Support for Print Preview

  1. From the Printing section of the Toolbox, click the PrintPreviewDialog icon Print Preview Dialog
  2. Click the form
  3. While the print preview control is still selected, in the Properties window, change its Name to dlgPrintPreview

Characteristics of the Print Preview

 

The Preview Area

The Print Preview window appears as a finished designed form with a toolbar, a preview area, and two scroll bars.

The preview area shows a sample of what a printed sheet would look like. If the dialog box is not "aware" of what would be printed, it displays the "Document does not contain any pages" string. This means that, in order to display something, you must create and design it. To make this possible, the PrintPreviewDialog class is equipped with a property named Document. The PrintPreviewDialog.Document property is of type PrintDocument. Therefore, in order to design a sample sheet, you should have created and configured a PrintDocument object. Here is an example:

using System;
using namespace System::Drawing;
using namespace System::Windows.Forms;
using namespace System::Drawing.Printing;

public class Exercise : Form
{
    Button btnPrintPreview;
    PrintPreviewDialog dlgPrintPreview;
    PrintDocument docPrint;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnPrintPreview = gcnew Button();
        btnPrintPreview->Location = Point(12, 12);
        btnPrintPreview->Text = "&Print Preview...";
        btnPrintPreview->Width = 100;
        btnPrintPreview.Click += gcnew EventHandler(PreviewDocumentClick);

        Controls.Add(btnPrintPreview);

        dlgPrintPreview = gcnew PrintPreviewDialog();
        docPrint = gcnew PrintDocument();

        dlgPrintPreview.Document = docPrint;
    }

    void PreviewDocumentClick(Object ^ sender, EventArgs ^ e)
    {
        dlgPrintPreview.ShowDialog();
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Print Preview

As you can see, simply assigning a PrintDocument object to a print preview form only creates a blank sheet. In order to show a preview, you must design it. To make this possible, the PrintDocument class

To assist you with actually designing what you want to display in the preview area, the PrintDocument class fires an event named PrintPage. This event is of type PrintPageEventArgs. The PrintPageEventArgs class is equipped with a property named Graphics, which is of type Graphics. You can then use your knowledge of the Graphics class to create or design the preview. Here is an example:

using System;
using namespace System::Drawing;
using namespace System::Windows.Forms;
using namespace System::Drawing.Printing;

public class Exercise : Form
{
    Button btnPrintPreview;
    PrintPreviewDialog dlgPrintPreview;
    PrintDocument docPrint;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnPrintPreview = gcnew Button();
        btnPrintPreview->Location = Point(12, 12);
        btnPrintPreview->Text = "&Print Preview...";
        btnPrintPreview->Width = 100;
        btnPrintPreview.Click += gcnew EventHandler(PreviewDocumentClick);

        Controls.Add(btnPrintPreview);

        dlgPrintPreview = gcnew PrintPreviewDialog();
        docPrint = gcnew PrintDocument();
        docPrint.PrintPage += gcnew PrintPageEventHandler(docPrintPage);

        dlgPrintPreview.Document = docPrint;
    }

    void PreviewDocumentClick(Object ^ sender, EventArgs ^ e)
    {
        dlgPrintPreview.ShowDialog();
    }

    void docPrintPage(Object ^ sender, PrintPageEventArgs ^ e)
    {
        Image imgPerson = Image::FromFile(@"E:\Programs\persons1.gif");
        e->Graphics->DrawImage(imgPerson, 10, 10);
    }
}

On our computer, this produced:

ApplicationPractical Learning: Showing Print Preview

  1. Still in the Properties window, click Document and select docPrint
  2. On the form click File and double-click Print Preview
  3. Implement the event as follows:
    System::Void printPreviewToolStripMenuItem_Click(System::Object^  sender,
    			System::EventArgs^  e)
    {
        dlgPrintPreview->ShowDialog();
    }
  4. Return to the form
  5. On its main menu, click File and double-click Exit
  6. Implement the event as follows:
    System::Void exitToolStripMenuItem_Click(
    	System::Object^  sender, System::EventArgs^  e)
    {
        Close();
    }

Printing From the Print Preview

To print the contents of the preview area, the user can click the Print button Print from the toolbar. Two things would happen. The compiler would select the default printer and the document would be sent directly to that printer. This means that, first there should be a (known) default printer and the user should know what that printer is; second, the user would not be able to change the printer if more than one is available. If you want the user to be able to select the printer, you should provide a Print dialog box that the user can probably access from a menu of the application.

Zooming the Preview

By default, when the print preview window appears to the user, it assumes some default dimensions that may make it small. Because it is derived from the Form class, you can maximize it if you want. Here is an example:

void PreviewDocumentClick(Object ^ sender, EventArgs ^ e)
{
        dlgPrintPreview.WindowState = FormWindowState.Maximized;
        dlgPrintPreview.ShowDialog();
}

If the print preview is not maximized, the content of the preview area may appear (too) small for the user, especially if it is made of text. To enlarge it, the user has two alternatives. If the user maximizes the window, the preview area would also be enlarged and the content would be easier to see. As an alternative, the user can click the arrow of the Zoom button. This would display a list of the zoom rates:

The user can then click one of the values.

ApplicationPractical Learning: Using Print Preview

  1. Execute the application
  2. Open a previously saved file
  3. On the main menu, click File -> Print Preview
     
    Watts A Loan
  4. Click the Print button
  5. Click the Close button

A Document of Various Pages

So far, we were assuming that the user was printing a one-page document. With some files, the document may span more than one page. By default, when the print preview comes up, the preview are would display only one page. The user has the choice of displaying two or more pages at a time, even to specify some arrangement of these pages. To support this, the toolbar of the print preview is equipped with various buttons labeled One Page, Two Pages, Three Pages, Four Pages, and Six Pages.

After using the print preview, the user can close it.

 
 
   
 

Home Copyright © 2004-2011 FunctionX, Inc.