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:

The Page Setup Dialog Box

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:

public sealed class PageSetupDialog : System.Windows.Forms.CommonDialog

Practical LearningPractical Learning: Introducing Page Setup

  1. Start Microsoft Visual Studio
  2. Create a Windows Forms App named MachineDepreciations2
  3. In the Solution Explorer, right-click Form1.cs and click Rename
  4. Type LoanEvaluation (to get LoanEvaluation.cs) and press Enter twice

The Name of a Printer

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:

Characteristics of the Page Setup Dialog Box

Displaying the Page Setup Printer dialog box also allows you and/or the user to customize the printing process if necessary. To support this, the PageSetupDialog class is equipped with a property named PrinterSettings:

public System.Drawing.Printing.PrinterSettings? PrinterSettings { get; set; }

As you can see, the PageSetupDialog.PrinterSettings property is a value of the PrinterSettings class reviewed already. 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.

Practical LearningPractical Learning: Adding a Page Setup Dialog Box

  1. From the Printing section of the Toolbox, click the PageSetupDialog icon
  2. Click the form
  3. While the print document control is still selected, in the Properties window, change its Name to dlgPageSetup

The Size of the Printer Paper(s)

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. 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.

Networked Printers a Font

If the desired printer is on a network, the user can click the Network button to locate it. To support this, the PageSetupDialog class is equipped with a Boolean property named ShowNetwork

public bool ShowNetwork { get; set; }

To programmatically show or hide the Network button, specify a false or true result to the PageSetupDialog.ShowNetwork Boolean property.

The Paper Orientation

The user has the option to print the document in Portrait (vertical) or in Landscape (horizontal) position. To support the option to allow the user to select Portrait or Landscape, the PageSetupDialog class is equipped with a read-write Boolean property named AllowOrientation:

public bool AllowOrientation { get; set; }

Practical LearningPractical Learning: Preparing the Page Setup Dialog Box

  1. While the print document control is still selected under the form, 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:
    private void mnuFilePageSetup_Click(object sender, EventArgs e)
    {
        dlgPageSetup.ShowDialog();
    }
  1. From the Menus & Toolbars section of the Toolbox, click MenuStrip and click the form
  2. Design the menu items as follows:
    MenuItem DropDownItems
    Text Name Text Name Image Shortcut
    &File mnuFile        
        &New Loan Evaluation mnuFileNew new.ico Ctrl+N
        &Open Loan Evaluation... mnuFileOpen open.ico Ctrl+O
        &Save Loan Evaluation mnuFileSave save.ico Ctrl+S
        Separator      
        Pa&ge Setup... mnuFilePageSetup    
        &Print... mnuFilePrint printer.ico Ctrl+P
        Print Pre&view... mnuFilePrintPreview    
        Separator      
        E&xit mnuFileExit    
  3. From the Printing section of the Toolbox, click the PrintDialog button PrintDialog
  4. Click the form
  5. While the print control is still selected, in the Properties window, change its Name to dlgPrint
  6. From the Printing section of the Toolbox, click the PrintDocument button PrintDocument
  7. Click the form
  8. While the print document control is still selected, in the Properties window, change its name to docPrint
  9. Under the form, click dlgPrint
  10. In the Properties window, click Document and select docPrint
  11. From the Dialogs section of the Toolbox, click OpenFileDialog and click the form
  12. Change its properties as follows:
    Title: Open Existing Loan Evaluation
    DefaultExt: rpr
    Filter: Watts A Loan (*.wal)|*.wal|All Files|
    Name: dlgOpen
  13. From the Dialogs section of the Toolbox, click SaveFileDialog and click the form
  14. Change its properties as follows:
    Title: Save Loan Evaluation
    DefaultExt: wal
    Filter: Watts A Loan (*.wal)|*.wal|All Files|
    Name: dlgSave
  15. Design the form as follows:

    Interest Rate

    Control Text Name TextAlign
    Label Prepared by:    
    TextBox   txtEmployeeName  
    Label Prepared for:    
    TextBox   txtCustomerName  
    GroupBox Loan Preparation    
    Label Principal    
    TextBox 0.00 txtPrincipal Right
    Label Interest Rate:    
    TextBox 0.00 txtInterestRate Right
    Label %    
    Label Periods:    
    TextBox 1 txtPeriods Right
    Label Months    
    Button Calculate btnCalculate  
    GroupBox Results    
    Label Interest Earned:    
    TextBox 0.00 txtInterestEarned Right
    Label Future Value   
    TextBox 0.00 txtFutureValue Right

    Interest Rate

  16. On the form, double-click the Calculate button
  17. Return to the form and, on the bar below the form, double-click docPrint to generate its default event
  18. Return to the form and, on the menu of the form, click File
  19. Double-click New Loan Evaluation
  20. Return to the form, click File and double-click Open Loan Evaluation
  21. Return to the form, click File and double-click Save Loan Evaluation
  22. Return to the form, click File and double-click Print
  23. Return to the form
  24. Implement its Click event as follows:
    1. Implement the PrintPage event as follows:
    2. On the form
    3. Implement the event as follows:
    4. Implement its Click event as follows:implement to generate its Click eventOn the form, and d as follows:
      private void btnCalculate_Click(object sender, EventArgs e)
      {
          decimal principal    = 0.00M,
                  interestRate = 0.00M,
                  interestEarned,
                  futureValue;
          decimal periods = 0.00M;
      
          try
          {
              principal = decimal.Parse(txtPrincipal.Text);
          }
          catch(Exeption exc) when exc as (FormatException fex)
          {
              MessageBox.Show("The value you entered for the " +
                              "principal is not valid");
          }
      
          try
          {
              interestRate = decimal.Parse(txtInterestRate.Text);
          }
          catch (FormatException)
          {
              MessageBox.Show("Wrong Value: The interest rate must " +
                              "be a value between 0 and 100");
          }
      
          try
          {
              periods = decimal.Parse(txtPeriods.Text);
          }
          catch (FormatException)
          {
              MessageBox.Show("You entered an invalid value for the periods");
          }
      
          decimal I = InterestRate / 100;
          decimal p = Periods / 12;
          
          interestEarned = Principal * I  * p;
          futureValue    = Principal + InterestEarned;
      
          txtInterestEarned.Text = InterestEarned.ToString("F");
          txtFutureValue.Text = FutureValue.ToString("F");
      }
      private void mnuFileNew_Click(object sender, 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";
      }
      using System;
      using System.ComponentModel;
      using System.Collections;
      using System.Windows.Forms;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.IO;
    5. Implement its Click event as follows:
      private void mnuFileOpen_Click(object sender, EventArgs e)
      {
          dlgOpen.InitialDirectory = @"C:\Watts A Loan";
      
          if (dlgOpen.ShowDialog() == DialogResult.OK)
          {
              FileStream fleWattsALoan = new FileStream(this.dlgOpen.FileName,
                     FileMode.Open, FileAccess.Read, FileShare.Read);
              BinaryReader bnrWattsALoan = new 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();
          }
      }
      private void mnuFileSave_Click(object sender, 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() == DialogResult.OK)
          {
              // Create a new file using the name of the Save dialog box
              FileStream fleWattsALoan = new FileStream(dlgSave.FileName,
                         FileMode.Create, FileAccess.Write, FileShare.Write);
              BinaryWriter bnrWattsALoan = new 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();
      
              mnuFileNew_Click(sender, e);
          }
      }
      private void docPrint_PrintPage(object sender,
                  System.Drawing.Printing.PrintPageEventArgs e)
      {
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 60, 90, 700, 90);
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 60, 93, 700, 93);
      
          string strDisplay = "Watts A Loan";
          System.Drawing.Font fntString = new Font("Times New Roman", 28,
                                                   FontStyle.Bold);
          e.Graphics.DrawString(strDisplay, fntString,
                                Brushes.Black, 280, 100);
      
          strDisplay = "Loan Evaluation";
          fntString = new System.Drawing.Font("Times New Roman", 18,
                                              FontStyle.Bold);
          e.Graphics.DrawString(strDisplay, fntString,
                                Brushes.Black, 320, 150);
      
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 60, 184, 700, 184);
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 60, 187, 700, 187);
      
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 250, 680, 250);
      
          fntString = new System.Drawing.Font("Times New Roman", 10,
                                              FontStyle.Bold);
          e.Graphics.DrawString("Prepared by:", fntString,
                                Brushes.Black, 100, 260);
          fntString = new System.Drawing.Font("Times New Roman", 10,
                                              FontStyle.Regular);
          e.Graphics.DrawString(txtEmployeeName.Text, fntString,
                                Brushes.Black, 260, 260); ;
      
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 280, 680, 280);
      
          fntString = new Font("Times New Roman", 10, FontStyle.Bold);
          e.Graphics.DrawString("Prepared for:", fntString,
              Brushes.Black, 100, 290);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
          e.Graphics.DrawString(txtCustomerName.Text, fntString,
              Brushes.Black, 260, 290); ;
      
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 310, 680, 310);
      
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 340, 680, 340);
      
          fntString = new Font("Times New Roman", 10, FontStyle.Bold);
          e.Graphics.DrawString("Principal:", fntString, Brushes.Black, 100, 350);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
      
          e.Graphics.DrawString(txtPrincipal.Text, fntString, Brushes.Black, 260, 350);
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 370, 680, 370);
      
          fntString = new Font("Times New Roman", 10, FontStyle.Bold);
          e.Graphics.DrawString("Interest Rate:", fntString,
              Brushes.Black, 100, 380);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
          e.Graphics.DrawString(txtInterestRate.Text, fntString,
                                Brushes.Black,
                                new RectangleF(260, 380, 420, 380));
          e.Graphics.DrawString("%", fntString, Brushes.Black, 300, 380);
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 400, 680, 400);
      
          fntString = new Font("Times New Roman", 10, FontStyle.Bold);
          e.Graphics.DrawString("Periods:", fntString,
                                Brushes.Black, 100, 410);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
          e.Graphics.DrawString(txtPeriods.Text, fntString,
                                Brushes.Black,
                                new RectangleF(260, 410, 400, 410));
          e.Graphics.DrawString("Months", fntString, Brushes.Black, 300, 410);
      
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 430, 680, 430);
      
          e.Graphics.DrawString("Interest Earned:", fntString,
                                Brushes.Black, 100, 440);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
          e.Graphics.DrawString(txtInterestEarned.Text, fntString,
                                Brushes.Black,
                                new RectangleF(260, 440, 420, 440));
      
          e.Graphics.DrawLine(new Pen(Color.Black, 1), 100, 460, 680, 460);
      
          e.Graphics.DrawString("Future Value:", fntString,
                                Brushes.Black, 100, 470);
          fntString = new Font("Times New Roman", 10, FontStyle.Regular);
          e.Graphics.DrawString(txtFutureValue.Text, fntString,
                                Brushes.Black,
                                new RectangleF(260, 470, 420, 470));
      
          e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 500, 680, 500);
      }
      private void mnuFilePrint_Click(object sender, EventArgs e)
      {
          if ( dlgPrint.ShowDialog() == 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
  25. To execute the application, press F5
  26. Create a new record. Here is an example:
     
    Watts A Loan
  27. On the main menu of the form, click File -> Save
  28. Set the file name to ep
  29. Click Save
  30. Create another loan and calculate it
     
    Watts A Loan
  31. Save it as hgm
  32. Close the form and return to your programming environment
  33. Press F5 to execute
  34. Try opening a previously saved order
  35. Close the form and return to your programming environment

Introduction to Print Preview

Introduction

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, click the PrintPreviewDialog button Print Preview Dialog 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 a class named PrintPreviewDialog. This class is derived from the Form class:

public class PrintPreviewDialog : System.Windows.Forms.Form

Based on this, to programmatically create a print preview, you can start by declaring a variable of type PrintPreviewDialog. Here is an example:

public class Exercise : Form
{
    Button btnPrintPreview;

    public Exercise()
    {
        InitializeComponent();
    }

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

        Controls.Add(btnPrintPreview);
    }

    void PreviewDocumentClick(object sender, EventArgs e)
    {
        PrintPreviewDialog dlgPrint = new PrintPreviewDialog();
    }
}

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

void PreviewDocumentClick(object sender, EventArgs e)
{
    PrintPreviewDialog dlgPrintPreview = new PrintPreviewDialog();

    dlgPrintPreview.ShowDialog();
}

This would produce:

Print Preview

Practical LearningPractical 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:

public System.Drawing.Printing.PrintDocument? Document { get; set; }

Therefore, in order to design a sample sheet, you should have created and configured a PrintDocument object. Here is an example:

using System.Drawing.Printing;

namespace PrintingIntroduction
{
    public partial class Exercise : Form
    {
        // Create a reference to a Print Document object
        PrintDocument docPrint;
        Button             btnPrintPreview;
        PrintPreviewDialog dlgPrintPreview;

        public Exercise()
        {
            InitializeComponent();
         
            dlgPrintPreview = new PrintPreviewDialog();
            
            // Initialize the Print Document object
            docPrint = new PrintDocument();

            // Specify the Print Document object as the document of the Print Preview object
            dlgPrintPreview.Document = docPrint;

            btnPrintPreview = new Button();
            btnPrintPreview.Location = new Point(12, 12);
            btnPrintPreview.Text = "&Print Preview...";
            btnPrintPreview.Click += (sender, e) =>
            {
                dlgPrintPreview.ShowDialog();
            };

            Controls.Add(btnPrintPreview);
        }
    }
}

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 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.Drawing.Printing;

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

        public Exercise()
        {
            InitializeComponent();
         
            dlgPrintPreview = new PrintPreviewDialog();
            docPrint = new PrintDocument();
            docPrint.PrintPage += (sender, e) =>
            {
                Image imgPerson = Image.FromFile(@"C:\Exercises\Persons.png");
                e.Graphics!.DrawImage(imgPerson, 10, 10);
            };

            dlgPrintPreview.Document = docPrint;

            btnPrintPreview = new Button();
            btnPrintPreview.Location = new Point(12, 12);
            btnPrintPreview.Text = "&Print Preview...";
            btnPrintPreview.Click += (sender, e) =>
            {
                dlgPrintPreview.ShowDialog();
            };

            Controls.Add(btnPrintPreview);
        }
    }
}

On our computer, this produced:

Practical LearningPractical 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:
    private void mnuFilePrintPreview_Click(object sender, 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:
    private void mnuFileExit_Click(object sender, EventArgs e)
    {
        Close();
    }

Printing From the Print Preview

To print the contents of the preview area, the user can click the Print button 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.

Practical LearningPractical 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 area 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.


Previous Copyright © 2004-2024, FunctionX Monday 14 February 2022 Home