15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Printing ❘ OC45<br />

}<br />

if (nLines > 0)<br />

{<br />

documentHasData = true;<br />

menuFilePrint.Enabled = true;<br />

menuFilePrintPreview.Enabled = true;<br />

}<br />

else<br />

{<br />

documentHasData = false;<br />

menuFilePrint.Enabled = false;<br />

menuFilePrintPreview.Enabled = false;<br />

}<br />

CalculateLineWidths();<br />

CalculateDocumentSize();<br />

Text = st<strong>and</strong>ardTitle + "-" + FileName;<br />

Invalidate();<br />

code download Printing.sln<br />

The above code is the new code added to this method. Next, you add a member field to the Form1 class:<br />

public partial class Form1: Form<br />

{<br />

private int pagesPrinted = 0;<br />

This field will be used to indicate which page you are currently printing. You are making it a member field<br />

because you will need to remember this information between calls to the PrintPage event h<strong>and</strong>ler.<br />

Next, you will find the event h<strong>and</strong>lers that h<strong>and</strong>le the selection of the Print or Print Preview menu options:<br />

private void menuFilePrintPreview_Click(object sender, System.EventArgs e)<br />

{<br />

this.pagesPrinted = 0;<br />

PrintPreviewDialog ppd = new PrintPreviewDialog();<br />

PrintDocument pd = new PrintDocument();<br />

pd.PrintPage += this.pd_PrintPage;<br />

ppd.Document = pd;<br />

ppd.ShowDialog();<br />

}<br />

private void menuFilePrint_Click(object sender, System.EventArgs e)<br />

{<br />

this.pagesPrinted = 0;<br />

PrintDocument pd = new PrintDocument();<br />

pd.PrintPage += new PrintPageEventH<strong>and</strong>ler<br />

(this.pd_PrintPage);<br />

pd.Print();<br />

}<br />

code download Printing.sln<br />

You have already seen the steps involved in printing, <strong>and</strong> you can see that these event h<strong>and</strong>lers are simply<br />

implementing that procedure. In both cases, you are instantiating a PrintDocument object <strong>and</strong> attaching an<br />

event h<strong>and</strong>ler to its PrintPage event. In the case of printing, you call PrintDocument.Print(), whereas<br />

for print previewing, you attach the PrintDocument object to a PrintPreviewDialog <strong>and</strong> call the preview<br />

dialog box object’s ShowDialog() method. The real work to the PrintPage event is done in the event<br />

h<strong>and</strong>ler. Here is how this h<strong>and</strong>ler looks:<br />

private void pd_PrintPage(object sender, PrintPageEventArgs e)<br />

{<br />

float yPos = 0;<br />

float leftMargin = e.MarginBounds.Left;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!