Module 6: Printing and Reporting in Windows Forms Applications

Module 6: Printing and Reporting in Windows Forms Applications
Module 6: Printing and
Reporting in Windows
Forms Applications
Contents
Overview
1
Lesson: Printing from a Windows Forms
Application
2
Lesson: Using the Print Preview,
Page Setup, and Print Dialogs
16
Lesson: Constructing Print Document
Content by Using GDI+
32
Lesson: Creating Reports by Using
Crystal Reports
47
Review
56
Lab 6.1: Printing Formatted Documents
58
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
 2002 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, Active X, Authenticode, FrontPage, IntelliSense,
MSDN, PowerPoint, Visual Basic, Visual C#, Visual Studio, Win32, and Windows Media are
either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 6: Printing and Reporting in Windows Forms Applications
Instructor Notes
Presentation:
150 minutes
Lab:
60 minutes
This module provides students with an overview of how to print and create
reports in Windows Forms applications, which are a part of the new
Microsoft® .NET Framework.
After completing this module, students will be able to:
„
Print documents in a Windows Forms application.
„
Use the printing dialog boxes of Microsoft Visual Studio® .NET in a
Windows Forms application.
„
Use GDI+ to construct print document content.
„
Create and format reports by using Crystal Reports.
Required materials
To teach this module, you need the Microsoft PowerPoint® file 2555A_06.ppt.
Preparation tasks
To prepare for this module:
„
Read all of the materials for this module.
„
Complete the demonstration, practices and lab.
iii
iv
Module 6: Printing and Reporting in Windows Forms Applications
How to Teach This Module
This section contains information that will help you to teach this module.
„
The duration of this module is approximately 90 minutes. However, if you
are running short of time, you should go through the slides quickly and then
let students do the practices. If students can complete their practices, they
will be able to meet the objectives of the module.
„
Before you start this module, find out how many students use Crystal
Reports. If this lesson is not important to your students, you can skip it.
„
Lab 6.1: Printing Formatted Documents is based on the Purchase Order
application in Course 2555A, Developing Microsoft .NET Applications for
Windows® (Visual C#™ .NET) and is intended to simulate a real-world
environment in which students will demonstrate what they learned during
the lecture and practice portions of the module. The lab does not provide
step-by-step detailed instructions; instead, the students are given tasks to
complete in the left column and a list of resources that they can use (if they
need help) in the right column. Students get the hands-on experience that
they need by completing the practice activities at the end of each lesson.
Lab 6: Printing Formatted Documents
• Make sure that you have demonstrated the two lab applications—the
Expense Report application and the Purchase Order application—in
Course 2555A, Developing Microsoft .NET Applications for Windows
(Visual C# .NET) before students begin the lab. To see how to demonstrate
the lab scenarios, see the Introduction module in Course 2555A, Developing
Microsoft .NET Applications for Windows (Visual C# .NET).
Module 6: Printing and Reporting in Windows Forms Applications
1
Overview
„
Printing from a Windows Forms Application
„
Using the Print Preview, Page Setup, and Print Dialogs
„
Constructing Print Document Content by Using GDI+
„
Creating Reports by Using Crystal Reports
Introduction
Any application developed for the Microsoft® Windows® operating system that
deals with data should include printing and reporting features for the users. This
module explores how to implement printing in a Windows Forms application
and how to create reports in a Windows Forms application by using Crystal
Reports for Microsoft Visual Studio® .NET.
Objectives
After completing this module, you will be able to:
„
Print documents in a Windows Forms application.
„
Use the Visual Studio .NET printing dialog boxes in a Windows Forms
application.
„
Use GDI+ to construct print document content.
„
Create and format reports by using Crystal Reports.
2
Module 6: Printing and Reporting in Windows Forms Applications
Lesson: Printing from a Windows Forms Application
„
How Printing Works in a .NET Windows Forms
Application
„
PrintDocument Object
„
PrintPage Event and PrintPageEventArgs
„
How to Enable Printing in a Windows Forms
Application
„
Practice: Adding Print Support to a Windows Forms
Application
Introduction
This lesson describes how to add basic print support to a Windows Forms
application. Most applications developed for Windows include the ability to
print some information. Visual Studio .NET provides components that simplify
the print process in your Windows Forms application and provides you with
control throughout the entire print process.
Lesson objectives
After completing this lesson, you will be able to:
„
Add a PrintDocument control to a form and create a PrintPage event
handler.
„
Add programming logic to a PrintPage event procedure to construct page
content.
„
Add programming logic to a PrintPage event procedure that enables your
application to print more than one page of content.
Module 6: Printing and Reporting in Windows Forms Applications
How Printing Works in a .NET Windows Forms Application
2. PrintPage event
• Construct content
• Support multi-page docs
How?
How?
Again,
Again,
How?
How?
3. PrintPageEventArgs parameter
• PageSettings property
• Graphics object
• HasMorePages property
1. PrintDocument object
• Enables printing
What
What
About
About User
User
Support?
Support?
5. Print method
• Sends content to printer
But
But How
How Do
Do II
Actually
Actually
Print?
Print?
4. Standard Dialog boxes for
printing
• PrintPreviewDialog
• PageSetupDialog
• PrintDialog
Introduction
Application developers who use Windows Forms will use the PrintDocument
class to support printing in their .NET Windows Forms applications. However,
the PrintDocument object is not the only component that you will be using
when printing documents in Windows Forms applications.
Print procedure
1. Add the PrintDocument object.
The PrintDocument object is central to printing in Windows Forms
applications.
2. Create the PrintPage Event handler.
The PrintDocument object uses the program logic that you create in the
PrintDocument.PrintPage event to construct the content of the print
document and indicate when additional pages must be generated.
3. Use the PrintPageEventArgs parameter.
The PrintPage event uses the PrintPageEventArgs parameter that it
receives to access and store information about the print document.
Applications will generally use the PageSettings property to read
information about document layout, construct page content by drawing text
and graphics on the Graphics object, and then indicate when additional
pages must be generated by setting the HasMorePages property.
Note More information about constructing print content by using the
Graphics object supplied by the PrintPageEventArgs parameter is included
in the lesson titled Constructing Print Document Content by Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for Windows
(Visual C#™ .NET).
3
4
Module 6: Printing and Reporting in Windows Forms Applications
4. Use the standard print dialog boxes available in Visual Studio .NET.
User support can be added by using the three standard dialog boxes that are
provided in the Design view of Toolbox. The standard dialog boxes provide
an easy way of adding powerful end user support in your applications with a
familiar user interface (UI).
Note More information about PrintPreviewDialog, PageSetupDialog, and
PrintDialog is included in the lesson titled Using the Print Preview, Page
Setup, and Print Dialogs in Module 6, “Printing and Reporting in Windows
Forms Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
5. Print the document by using the Print method.
The PrintDocument.Print method is used to enable actual document
printing.
Module 6: Printing and Reporting in Windows Forms Applications
PrintDocument Object
„
PrintDocument object
z
Provides the ability to print a document
z
Provides properties that describe what to print
PrintDocument
PrintDocument
Properties
Properties
PrintDocument
PrintDocument
Events
Events
PrintDocument
PrintDocument
Methods
Methods
DefaultPageSettings
DefaultPageSettings
BeginPrint
BeginPrint
Dispose
Dispose
DocumentName
DocumentName
EndPrint
EndPrint
Print
Print
PrintController
PrintController
PrintPage
PrintPage
PrinterSettings
PrinterSettings
QueryPageSettings
QueryPageSettings
Note: The check marks indicate the most commonly used properties, events,
and methods of the PrintDocument object
Introduction
The PrintDocument object is central to printing in Windows Forms
applications. You use PrintDocument to set properties that specify what to
print and to provide the properties, events, and methods that are required to
print documents. The PrintDocument object is added to a Form from the
Toolbox at design time, but an instance of the PrintDocument class can be
declared at run time as well.
PrintDocument
properties
The DefaultPageSettings property gets or sets page settings that are used as
defaults for all pages to be printed.
The PrinterSettings property can be used to get or set the printer that prints the
document, modify the properties of the selected printer, and modify settings
associated with the print job such as the number of copies that will be printed.
The following table describes some additional properties of the
PrintDocument object that you can use to customize a print job.
Property
Description
DocumentName
Gets or sets the document name to display while printing
the document.
PrintController
Gets or sets the print controller that guides the printing
process.
For more information and a complete list of the properties of the
PrintDocument object, in the Visual Studio .NET Help documentation, search
by using the phrase PrintDocument members.
5
6
Module 6: Printing and Reporting in Windows Forms Applications
PrintDocument events
The PrintPage event is used to generate the content of the print document, and
it is in the PrintPage event handler that you must include your own code to
indicate when the document has additional pages of content to print.
The following table describes some additional events of the PrintDocument
object that enable you to print output.
Event
Description
BeginPrint
Occurs when the Print method is called and before the
first page of the document prints. One example of when
to use BeginPrint is when you want to notify the user
about how many pages there are in a print job.
EndPrint
Occurs when the last page of the document has printed.
One example of when EndPrint can be used is when you
want to signal the user that the print job has completed.
QueryPageSettings
Occurs immediately before each PrintPage event. You
can use QueryPageSettings when you want to use
different PageSettings for one or more pages of a print
document.
For more information and a complete list of the events of the PrintDocument
object, in the Visual Studio .NET Help documentation, search by using the
phrase PrintDocument members.
PrintDocument methods
After you have established the printer and default page settings and constructed
the contents of the print document, you will use the Print method to start the
print process. The Print method sends the contents of the print document to the
printer by passing the print device a Graphics object that acts as a container for
the content. The Graphics object is discussed in more detail in the PrintPage
Event and PrintPageEventArgs topic in this module.
The Dispose method releases the resources used by the PrintDocument
component.
For more information and a complete list of the methods of the PrintDocument
object, in the Visual Studio .NET Help documentation, search by using the
phrase PrintDocument members.
Module 6: Printing and Reporting in Windows Forms Applications
7
PrintPage Event and PrintPageEventArgs
PrintPage Event
• The PrintPage event includes
two parameters: an object
representing the Sender and a
PrintPageEventsArgs object
• The PrintPage event
procedure contains the
programming logic that
constructs the contents of the
print document and ensures
that the entire print document
is printed
PrintPagesEventArgs Object
• The PrintPageEventArgs
object provides the
components required to
construct the pages of the
print document
• PageSettings, Graphics,
and HasMorePages are
the critical members
Introduction
A PrintDocument.PrintPage event occurs for every page of a print document
that is displayed or printed. You create a procedure to handle the PrintPage
event and populate it with the code used to construct the content of the print
document.
PrintPage event
procedure
The event procedure that handles the PrintDocument.PrintPage event has two
parameters: the object representing the sender that fired the event
(PrintDocument) and the PrintPageEventArgs object. The procedure that you
create to handle the PrintPage event contains the programming logic required
to construct the print document (using the components supplied by the
PrintPageEventArgs object). The PrintPage event procedure also contains the
programming logic that you develop to indicate when an additional page of
content must be generated.
Members of the
PrintPageEventArgs
parameter
The PrintPageEventArgs parameter contains all the data required to construct a
page of the print document. The PrintPageEventArgs object has six member
components, including the Graphics object that is used as the “paper” on which
the contents of a page are drawn. The other two most critical members are the
HasMorePages property that you must set to True when there are more pages
to print, and the PageSettings property that can be used to read the page setting
values for the current page.
The other three properties of the PrintPageEventArgs parameter are Cancel,
MarginBounds, and PrintBounds. You can use the Cancel property to stop
the construction of document pages before the end of the print document and
the PagesBounds and MarginBounds properties to return the size of the
current page and the size of the page inside the margins, respectively (both of
which can be determined by using the PageSettings property).
8
Module 6: Printing and Reporting in Windows Forms Applications
PrintPageEventArgs.
PageSettings
The PageSettings property supplied by the PrintPageEventArgs parameter is a
read-only property that is used to get page settings for the current page.
PageSettings includes Bounds and Margins members that supply the same
information found in the PageBounds and MarginBounds properties.
Note To modify page settings, you must handle the QueryPageSettings event
of the PrintDocument object.
The following example demonstrates how to use the PageSettings and
MarginBounds properties inside a PrintPage event handler to determine the
location of the left margin and the number of text lines that will fit on a page for
a given font.
…
LeftMargin = e.PageSettings.Margins.Left;
LinesPP = e.MarginBounds.Height/myFont.GetHeight(e.Graphics);
…
PrintPageEventArgs.
Graphics
The Graphics object supplied by the PrintPageEventArgs parameter acts as a
canvas for each page of a print document. You use the GDI+ drawing methods
of the Graphics object to draw the text and graphics contents of the page. For
example, to draw text inside a PrintPage event handler, you could use the
Graphics.DrawString method as follows:
…
e.Graphics.DrawString(" text will go here.", myFont,
myBrush, X, Y);
…
Note More information about constructing print content by using the Graphics
object supplied by the PrintPageEventArgs parameter is included in the lesson
titled Constructing Print Document Content by Using GDI+ in Module 6,
“Printing and Reporting in Windows Forms Applications,” in Course 2555A,
Developing Microsoft .NET Applications for Windows (Visual C# .NET).
Module 6: Printing and Reporting in Windows Forms Applications
PrintPageEventsArgs.
HasMorePages
9
The HasMorePages property supplied by the PrintPageEventArgs parameter is
a Boolean value that is False by default. You must manually set the value of the
HasMorePages property to True to indicate that an additional page should be
printed. The following example demonstrates how to set the HasMorePages
property to True when the next line of text would occur below the bottom
margin on the page.
// for each text line that will fit on the page,
//
read a new line from the document
while (CurrentLine < LinesPerPage)
{
TextLine = StreamToPrint.ReadLine();
if(TextLine == null)
{
break;
}
// set the vertical position on the page based
//
on the current line number
VerticalPosition = TopMargin +
CurrentLine * MyFont.GetHeight(e.Graphics);
// draw the text on the page
e.Graphics.DrawString(TextLine,
MyFont,
MyBrush,
HorizontalPosition,
VerticalPosition);
// increment the line number
CurrentLine += 1;
}
// If more lines of text exist in the file,
//
print another page.
if (TextLine != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
10
Module 6: Printing and Reporting in Windows Forms Applications
How to Enable Printing in a Windows Forms Application
Print
Print Page
Page Event
Event
PrintPagesEventArgs
PrintPagesEventArgs Class
Class
PrintPageEventArgs
•• Use
Use the
the
class
class to
to read
read page
page settings
settings such
such
as
as margins
margins and
and page
page height
height and
and
width
width
•• Establish
Establish fonts
fonts and
and brushes
brushes used
used
in
in your
your output
output
•• Establish
Establish regions
regions on
on the
the page
page
•• Construct
Construct output
output by
by positioning
positioning
text
text and
and graphics
graphics by
by using
using the
the
methods
methods of
of the
the Graphics
Graphics class
class
• Graphics Object
• HasMorePages
• PageSettings
DefaultPageSettings
DefaultPageSettings
PrintDocument
PrintDocument Object
Object
Print
Print Method
Method
•• Calls
Calls PrintPage
PrintPage
•• Checks
Checks HasMorePages
HasMorePages
•• Specify
Specify print
print settings
settings
•• Add
Add printing
printing logic
logic to
to PrintPage
PrintPage
Event
Event
•• Call
Call the
the Print
Print method
method
DIALOGS
DIALOGS
•• Document
Document property
property of
of the
the
Dialogs
Dialogs set
set to
to the
the
PrintDocument
PrintDocument object
object
Introduction
To print from a Windows Form application, you will use a PrintDocument
object to define the printer and characteristics of the print job, add programming
logic to the PrintPage event, provide your users with run-time support (by
using the standard dialog boxes provided in Visual Studio .NET), and then call
the Print method.
Procedure: Enabling
printing in a Windows
Forms application
To print a text document from a Windows Form application, you perform the
following procedure:
1. Add an instance of the PrintDocument class to your application and create
a PrintPage event procedure.
To add a PrintDocument control to a Form, open the Toolbox, and then
double-click PrintDocument. To create a PrintPage procedure, open the
Design view of the Form, click printDocument1. Then, in the Properties
window, click the Events button, and then double-click PrintPage.
2. Begin adding programming logic to the PrintDocument1_PrintPage
procedure to construct the content of the print document.
You can use the PageSettings property to define text and graphics regions
on the page. A simple example is assigning the value of
PageSettings.Margins.Left to a variable that will be used to position text on
the left side of the page. You must use the GDI+ drawing methods of the
PrintPageEventArgs.Graphics object to construct the contents of the print
document page.
Module 6: Printing and Reporting in Windows Forms Applications
11
3. Add support for previewing your print document so that you can test the
code that you developed up to this point. One simple way to preview your
print document is to add a PrintPreviewControl to your Form from the
Toolbox.
4. Add additional programming logic to the PrintDocument1_PrintPage
procedure that uses the HasMorePages property to indicate whether or not
more pages must be printed. The manner in which you determine whether
HasMorePages should be set to True depends on how your print document
is being constructed.
12
Module 6: Printing and Reporting in Windows Forms Applications
Practice: Adding Print Support to a Windows Forms Application
In this practice, you will
z
Add a PrintDocument control to a project
z
Create a PrintPage event procedure and
develop code to construct the contents of
a print document
z
Set the value of the HasMorePages
property to indicate when more pages
should be printed
Begin reviewing the objectives
for this practice activity
8 min
Introduction
In this practice, you will add print support to a Windows Forms application.
The practice involves adding a PrintDocument control to a project, creating a
procedure to handle the PrintPage event, adding programming logic to the
PrintPage procedure, and using the HasMorePages property. You will see
some questions in between some steps. Try and answer the question before you
move to the next step.
Instructions
Ç Open the practice project
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_01\Starter.
Note If you performed a default installation of the course files,
install_folder corresponds to C:\Program Files\Msdntrain\2555.
2. Double-click the PrintProcess.sln solution file to open the project.
Module 6: Printing and Reporting in Windows Forms Applications
13
Ç Add the PrintDocument control to your application
1. In Solution Explorer, click Form1.cs, and then click the View Designer
icon.
2. In the Toolbox, scroll down until you see the PrintDocument control, and
then double-click PrintDocument.
3. What functionality does the PrintDocument class provide to your
application?
The PrintDocument class enables a Windows Forms application to
initiate the print process (by calling the PrintDocument.Print method)
and provides access to printer and page settings that can be used to
control the appearance of your print document.
____________________________________________________________
____________________________________________________________
____________________________________________________________
Ç Create a custom PrintPage procedure
1. In Solution Explorer, click Form1.cs, and then click the View Code icon.
2. On the View menu, point to Show Tasks, and then click Comment.
3. In the Task List, double-click TODO: Add PrintPage event constructor.
4. Add the following code statement below the TODO line and press ENTER.
this.printDocument1.PrintPage +=
new System.Drawing.Printing.PrintPageEventHandler(
this.MyPrintPage);
5. What is the purpose of the PrintDocument.PrintPage event?
You will use the procedure that handles the PrintDocument.PrintPage
event to construct each page of a print document individually, to
control the number of print document pages that are created, to adjust
the page settings for each page of a print document, and to cancel a
print job when required. The Graphics object of the
PrintPageEventArgs parameter is used to construct the contents of each
page individually. The Graphics object will be passed to the print
device by using the PrintDocument.Print method.
____________________________________________________________
____________________________________________________________
____________________________________________________________
14
Module 6: Printing and Reporting in Windows Forms Applications
6. In the Task List, double-click TODO: create the PrintPage event handler.
7. Add the following code statements below the TODO line and press ENTER.
private void MyPrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawString("Page " + currentPage.ToString() +
" text will go here.", myFont, myBrush, X, Y);
if (currentPage < totalPages)
{
currentPage += 1;
}
}
8. Press F5, and then click Print Preview.
9. Close the PrintPreviewDialog dialog box.
10. Use the NumericUpDown control to add a second page to your print
document, and then preview your document again.
11. Why doesn’t your application display more than one page?
The HasMorePages property of the PrintPageEventArgs object is False
by default. You must develop the programming logic for a print loop
when the print job includes more than one document page.
____________________________________________________________
____________________________________________________________
12. Close the PrintProcess application.
Ç Create a print loop to ensure that all of the document pages are printed
1. Modify the contents of the if statement near the bottom of your
MyPrintPage procedure so that it appears as follows:
if (currentPage < totalPages)
{
currentPage += 1;
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
2. Start the PrintProcess application.
3. Use the NumericUpDown control to add a second page to your document,
and then preview your print document again. You should now be able to see
both pages of your print document.
Module 6: Printing and Reporting in Windows Forms Applications
Ç Close your application and Visual Studio .NET
If time permits, use the two buttons at the bottom of Form1 to display some
additional information that is available through the PrintDocument object, and
then examine the underlying code.
1. Close the PrintProcess application.
2. Save the PrintProcess application.
3. Close Visual Studio .NET.
15
16
Module 6: Printing and Reporting in Windows Forms Applications
Lesson: Using the Print Preview, Page Setup, and Print
Dialogs
„
How to Use the PrintPreviewDialog Control
„
Practice: Using the PrintPreviewDialog Control
„
How to Use the PageSetupDialog Control
„
Practice: Using the PageSetupDialog Control
„
How to Use the PrintDialog Control
„
Practice: Using the PrintDialog Control
Introduction
Visual Studio .NET includes three preconfigured dialog boxes—
PrintPreviewDialog, PageSetupDialog, and PrintDialog—that enable your
application user to preview a print document, specify page settings, and
establish the printer and print job settings from a Windows Forms application.
Using these preconfigured dialog boxes in a Windows Forms application not
only eases development, but also provides a clean, efficient, and familiar
interface to the end users. This lesson explains how to use the three print dialog
boxes in a Windows Forms application.
Lesson objectives
After completing this lesson, you will be able to:
„
Display a print preview of the print document by using the
PrintPreviewDialog and PrintPreviewControl controls.
„
Use a PrintPreviewControl control to preview your print document.
„
Specify page settings for a document by using the PageSetupDialog
control.
„
Select a printer and settings for the print job by using the PrintDialog
control.
Module 6: Printing and Reporting in Windows Forms Applications
17
How to Use the PrintPreviewDialog Control
PrintPreviewDialog
„
„
Use PrintPreviewDialog to display how a document will
appear when printed
To display a print preview of a document
1. Create an instance of the PrintPreviewDialog component
2. Set the Document property to the PrintDocument object
3. Configure the desired display settings for the
PrintPreviewDialog and the included PrintPreviewControl
4. Display the dialog by using the ShowDialog method
CodeExample
Introduction
A common feature of applications is the ability to display a preview of the
document to be printed. In Windows Forms applications, this feature is
provided by using the PrintPreviewDialog control. The PrintPreviewDialog
contains a PrintPreviewControl as well as controls for printing, zooming,
displaying one or multiple pages, and closing the dialog box. The standard
PrintPreviewDialog provides the user with a familiar tool for previewing
documents, but you can develop your own custom preview form by using the
same PrintPreviewControl used by the PrintPreviewDialog when your
application or users require something different.
Procedure
To use the PrintPreviewDialog to display a print preview of a document:
1. Add a PrintPreviewDialog control to your project by using the Toolbox, or
create a PrintPreviewDialog at run time by using code such as this:
PrintPreviewDialog previewDialog = new
PrintPreviewDialog();
2. Set the Document property of the PrintPreviewDialog control to the
PrintDocument component.
After you have created a PrintPreviewDialog object, you must set its
Document property to the PrintDocument object of your print document.
You can set the Document property in the Properties window of the
PrintPreviewDialog control at design-time or with the following code at
run time:
previewDialog.Document = PrintDocument1;
18
Module 6: Printing and Reporting in Windows Forms Applications
3. Properties of the PrintPreviewDialog, and the included
PrintPreviewControl, can be used to establish display settings showing the
dialog box:
previewDialog.WindowState =
FormWindowState.Maximized;
previewDialog.PrintPreviewControl.StartPage = 0;
previewDialog.PrintPreviewControl.Zoom = 1.0;
4. Display the PrintPreviewDialog by using the ShowDialog method.
Like all other dialog boxes, you can use the ShowDialog method to display
the PrintPreview dialog box at run time:
previewDialog.ShowDialog();
Example
The following code shows an example of how to use the PrintPreviewDialog
control to display a print preview of a document. The example assumes that a
PrintPreviewDialog control and a PrintDocument control were added to a
Form and that the PrintPreview procedure is called from an event handler.
private void PrintPreview()
{
// ensure that the first page of the print document is shown
printPreviewDialog1.PrintPreviewControl.StartPage = 0;
// display the document two pages at a time
printPreviewDialog1.PrintPreviewControl.Columns = 2;
// maximize the size of the dialog box on the display screen
printPreviewDialog1.WindowState = FormWindowState.Maximized;
// display the contents of the appropriate print document
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
PrintPreviewControl
The PrintPreviewControl is supplied in the Toolbox as a separate control that
you can use to preview a print document. You use the PrintPreviewControl
control when you want to define your own print-preview user interface. It has
no buttons or other user interface elements.
Some of the properties of the PrintPreviewControl control include Zoom,
Columns, Rows, and StartPage. These properties are available whether you
are using the PrintPreviewControl separately or as part of the
PrintPreviewDialog.
PrintPreviewControl.Columns = 2;
PrintPreviewDialog.PrintPreviewControl.Columns = 2;
For more information about PrintPreviewControl, in the Visual Studio .NET
Help documentation, search by using the phrase PrintPreviewControl.
Module 6: Printing and Reporting in Windows Forms Applications
19
Practice: Using the PrintPreviewDialog Control
In this practice, you will
z
Add a PrintPreviewDialog control
z
Create a PrintPreview subroutine
z
Modify the display settings for the
PrintPreviewDialog dialog box
Begin reviewing the objectives for
this practice activity
8 min
Introduction
In this practice, you will add a PrintPreviewDialog control and program logic
to a project so that application users can preview a document before printing it.
Instructions
Ç Open the practice project
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_02\Starter.
2. Double-click the PrintPreviewDialog.sln solution file to open the project.
Ç Add the PrintPreviewDialog control to your application
1. In Solution Explorer, click Form1.cs, and then click View Designer.
2. In the Toolbox, scroll down until you see the PrintPreviewDialog control,
and then double-click PrintPreviewDialog.
3. Where does the PrintPreviewDialog appear in the Design View window?
The PrintPreviewDialog control is added to the component tray at the
bottom of the Design View window.
____________________________________________________________
____________________________________________________________
20
Module 6: Printing and Reporting in Windows Forms Applications
Ç Create a PrintPreview procedure that displays the print document
1. In Solution Explorer, click Form1.cs, and then click View Code.
2. On the View menu, point to Show Tasks, and then click Comment.
3. In the Task List, double-click TODO: create PrintPreview procedure.
4. Add the following code statements below the TODO line.
private void PrintPreview()
{
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
5. Run the PrintPreviewDialog application, and use the menu or button to
display the print document.
6. Is there a way to make the dialog box larger by default?
Yes. The WindowState property of the dialog box can be used to set the
default window state to Maximized.
____________________________________________________________
7. Close the PrintPreviewDialog application.
Ç Modify the display settings for the PrintPreviewDialog dialog box
1. Add the following code line to the top of the PrintPreview procedure.
printPreviewDialog1.WindowState =
FormWindowState.Maximized;
2. Run the PrintPreviewDialog application, and use the menu or button to
display the print document.
3. Change the displayed page number to page 4, and then close the dialog box.
4. Redisplay the print document. Notice that the starting page is the page that
was displayed when the dialog box was closed.
5. Close the application, and then add the following code lines to the top of the
PrintPreview procedure.
printPreviewDialog1.PrintPreviewControl.StartPage = 0;
printPreviewDialog1.PrintPreviewControl.Zoom = 1.0;
6. Run the PrintPreviewDialog application, and use the menu or button to
display the print document. Verify that the Print Preview dialog box
always shows page 1 at 100% when opened.
7. Optional: Open the PrintPreviewDialog, change the page that is being
displayed to page 2, and then close and reopen the preview dialog box to
verify that the initial page displayed is always page 1.
8. Close the dialog box, and then close the application.
Module 6: Printing and Reporting in Windows Forms Applications
If time permits
21
Ç Examine some additional methods for displaying a print document
1. In Design view, enable the two other buttons on Form1.
2. Start the application, and use each button to display the print document.
3. Close the application, and examine the code used to display the document.
4. When would you want to use a PrintPreviewControl rather than a
PrintPreviewDialog to display a print document?
You would use a PrintPreviewControl to display a document when you
need to customize the print preview capabilities of an application.
____________________________________________________________
____________________________________________________________
5. Close the solution.
22
Module 6: Printing and Reporting in Windows Forms Applications
How to Use the PageSetupDialog Control
PageSetupDialog
„
Use PageSetupDialog to set page details in Windows
Forms applications
z Border and margin adjustments
z Headers and footers
z Portrait vs. landscape
„
To use PageSetupDialog to specify page settings
1. Create an instance of the PageSetupDialog control
2. Use ShowDialog to display the dialog at run time
3. Specify document settings by using the
DefaultPageSettings property or PageSettings class
CodeExample
Introduction
The PageSetupDialog control is a pre-configured dialog box that you can use
to set page layout details for printing in Windows Forms applications. The
PageSetupDialog control provides an easy solution to specify page settings
instead of configuring your own dialog box. With PageSetupDialog, you can
allow users to set border and margin adjustments, headers and footers, and
portrait versus landscape orientation by using a familiar tool.
Procedure: Using the
PageSetupDialog
To use PageSetupDialog to specify page settings:
1. Create an instance of PageSetupDialog.
The first step in using the PageSetupDialog in a Windows Forms
application is to add a PageSetupDialog control to your form from the
Toolbox or create a new instance of the PageSetupDialog control in code as
shown below.
PageSetupDialog PageDlg = new PageSetupDialog();
2. Supply PageSetupDialog with a PageSettings object that can be used to
store page settings and used for both the PrintDocument object and the
PageSetupDialog.
…
PageDlg.PageSettings = MyPageSettings;
Module 6: Printing and Reporting in Windows Forms Applications
23
3. Use the ShowDialog method to display the dialog box at run time.
To display the dialog box at run time, use the ShowDialog method as shown
in the following code.
PageDlg.ShowDialog();
4. Apply the modified page settings to your PrintDocument object.
To apply the new page settings to your document, use the
DefaultPageSettings property of the PrintDocument object.
printDocument1.DefaultPageSettings = MyPageSettings;
Example
The following code shows an example of how to use the PageSetupDialog
control.
private void PageSetup()
{
try {
PageSetupDialog pageDialog = new PageSetupDialog();
if (storedPageSettings == null) {
storedPageSettings = new PageSettings();
}
pageDialog.PageSettings = storedPageSettings ;
pageDialog.ShowDialog();
}
catch(Exception ex) {
MessageBox.Show("An error occurred - " + ex.Message);
}
}
Customize sections of
the PageSetup dialog
box
The user can enable sections of the PageSetup dialog box to manipulate
printing, margin, and paper orientation, and size.
Use the Margins and MinMargins properties to specify margins.
pageSetupDialog1.PageSettings.Margins.Top = 200;
pageSetupDialog1.PageSettings.Margins.Left = 200;
pageSetupDialog1.PageSettings.Margins.Bottom = 100;
pageSetupDialog1.PageSettings.Margins.Right = 100;
pageSetupDialog1.MinMargins.Top = 85;
pageSetupDialog1.MinMargins.Left = 75;
pageSetupDialog1.MinMargins.Bottom = 100;
pageSetupDialog1.MinMargins.Right = 100;
Set the AllowPrinter, AllowOrientation, and AllowPaper properties to True
to allow users to specify these properties.
pageSetupDialog1.AllowOrientation = false;
pageSetupDialog1.AllowPaper = false;
pageSetupDialog1.AllowPrinter = false;
24
Module 6: Printing and Reporting in Windows Forms Applications
Practice: Using the PageSetupDialog Control
In this practice, you will
z
Add a PageSetupDialog control to your
application
z
Create a PageSetup subroutine that
displays page settings
z
Assign the page settings to the
PrintDocument object
Begin reviewing the objectives for
this practice activity
8 min
Introduction
In this practice, you will add a PageSetupDialog control and program logic to a
project so that application users can specify page settings before printing a
document.
Instructions
Ç Open the practice project
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_03\Starter.
2. Double-click the PageSetupDialog.sln solution file to open the project.
Ç Add the PageSetupDialog control to your application
1. In Solution Explorer, click Form1.cs, and then click View Designer.
2. In the Toolbox, scroll down until you see the PageSetupDialog control, and
then double-click PageSetupDialog.
3. Where does the PageSetupDialog control appear in the Design View
window?
The PageSetupDialog control is added to the component tray at the
bottom of the Design View window.
____________________________________________________________
Module 6: Printing and Reporting in Windows Forms Applications
25
Ç Create a PageSetup procedure that displays page settings
1. In Solution Explorer, click Form1.cs, and then click View Code.
2. On the View menu, point to Show Tasks, and then click Comment.
3. In the Task List, double-click TODO: create PageSetup procedure.
4. Add the following code statements below the TODO line.
private void PageSetup()
{
pageSetupDialog1.ShowDialog();
}
5. Run the PageSetupDialog application, and use the menu or button to display
the Page Setup dialog box. Why does an error occur?
The PageSetupDialog control requires that you supply a PageSettings
object that represents the page settings for the document.
____________________________________________________________
6. Close the application, and then add the following code lines to the top of the
PageSetup procedure.
myPageSettings = new PageSettings();
pageSetupDialog1.PageSettings = myPageSettings;
7. Run the PageSetupDialog application, and display the Page Setup dialog
box.
8. Change the Top and Left margins to 0.5 inches, and then click OK.
9. Display a preview of the print document. Why didn’t the new settings take
effect?
Although the PageSetupDialog automatically places the new settings
into the MyPageSettings object, you still have to assign the page settings
to the PrintDocument object.
____________________________________________________________
____________________________________________________________
10. Close the PrintPreviewDialog and the application.
Ç Assign the page settings to the PrintDocument object
1. Add the following code lines to the bottom of the PageSetup procedure.
if (myPageSettings != null)
{
printDocument1.DefaultPageSettings = myPageSettings;
}
2. Run the PageSetupDialog application, and use the menu or button to display
the PageSetup dialog box.
3. Change the Top and Left margins to 0.5 inches, and then preview the print
document.
4. Reopen the PageSetup dialog box. Notice that the page settings are lost.
26
Module 6: Printing and Reporting in Windows Forms Applications
5. Click Cancel, close the application, and then, in the PageSetup procedure,
replace the "myPageSettings = new PageSettings();" code line with the
following code lines.
if (myPageSettings == null)
{
myPageSettings = new PageSettings();
}
6. Run the PageSetupDialog application, and use the PageSetup dialog box to
modify the document’s page settings. Notice that settings are not lost when
the dialog box is closed.
7. Close the application.
If time permits
Ç Examine some additional members of the PageSetupDialog control
1. In the Code Editor, examine the code in the pageSetupButton_Click
procedure.
2. Remove the comment characters from the front of the code lines one section
at a time, and view the changes to the PageSetup dialog box and the Print
Preview dialog box by running the application and opening the two dialog
boxes.
3. How could you use these additional members of the PageSetupDialog
control?
These additional members could be used to customize the
PageSetupDialog and control the range of settings that a user is allowed
to select.
____________________________________________________________
____________________________________________________________
4. Close the application and Visual Studio .NET.
Module 6: Printing and Reporting in Windows Forms Applications
27
How to Use the PrintDialog Control
PrintDialog
„
„
Use PrintDialog to specify printer-related settings
z Specify printer and print job properties
z Specify print range and collate settings
To use a PrintDialog control for users to select a printer
1. Create an instance of the PrintDialog component
2. Set the Document property to the PrintDocument object
3. Capture user input by using the DialogResult property
and display the Print dialog box
CodeExample
Introduction
Often, users will need to select a printer or set print properties before a
particular print job. This can be done by using the PrintDialog control.
Procedure
To use the PrintDialog control to print a document:
1. Add a PrintDialog control to your project by using the Toolbox, or create
an instance of the PrintDialog control at run time as follows:
PrintDialog printDialog = new PrintDialog();
2. Set the Document property of the PrintDialog object to the PrintDocument
component.
You must set the Document property of the PrintDialog control to the
PrintDocument object for document you are printing. Set the Document
property of the PrintDialog control at design time in the Properties window,
or at run time by using code, as follows:
printDialog.Document = printDocument1;
3. Capture the user’s response to the PrintDialog by using a DialogResult
object when constructing the code statement that displays the dialog box.
...
DialogResult UserResponse = printDialog.ShowDialog();
28
Example
Module 6: Printing and Reporting in Windows Forms Applications
The following code uses the PrintDialog control to provide the user with an
opportunity to modify printer and print job settings before printing the
document.
private void PrintDoc()
{
PrintDialog1.Document = PrintDocument1;
DialogResult userResponse;
userResponse = PrintDialog1.ShowDialog();
if (userResponse == DialogResult.OK)
{
PrintDocument1.Print();
}
}
Module 6: Printing and Reporting in Windows Forms Applications
29
Practice: Using the PrintDialog Control
In this practice, you will
z
Add a PrintDialog control to your
application
z
Create a PrintDoc subroutine that
displays the print dialog
z
Print a document by using the
PrintDocument.Print method
Begin reviewing the objectives for
this practice activity
8 min
Introduction
In this practice, you will add a PrintDialog control and program logic to a
project so that application users can specify printer and print job settings before
printing a document.
Instructions
Ç Open the practice project
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_04\Starter.
2. Double-click the PrintDialog.sln solution file to open the project.
Ç Add the PrintDialog control to your application
1. In Solution Explorer, click Form1.cs, and then click the View Designer
icon.
2. In the Toolbox, scroll down until you see the PrintDialog control, and then
double-click PrintDialog.
3. Where does the PrintDialog control appear in the Design View window?
The PrintDialog control is added to the component tray at the bottom
of the Design View window.
____________________________________________________________
30
Module 6: Printing and Reporting in Windows Forms Applications
Ç Create a PrintDoc procedure that displays the Print dialog box
1. Open Form1 in the Code Editor.
2. On the View menu, point to Show Tasks, and then click Comment.
3. In the Task List, double-click TODO: create PrintDoc procedure.
4. Add the following code statements below the TODO line.
private void PrintDoc()
{
printDialog1.ShowDialog();
}
5. Run the PrintDialog application, and click the menu item or button that is
used display the Print dialog box. Why doesn’t the Print dialog box open?
The PrintDialog.Document property must be set before the PrintDialog
can be displayed.
____________________________________________________________
6. Close the application, and then add the following code line to the top of the
PrintDoc procedure.
printDialog1.Document = printDocument1;
Ç Print a document by using the PrintDocument.Print method
1. Run the PrintDialog application, and then display the Print dialog box.
2. Click OK.
3. Why didn’t the document print?
The PrintDialog does not call the PrintDocument.Print method—you
must add code to do this yourself. However, this means that you have to
know which dialog box button the user clicked. You can determine this
by using a DialogResult object.
____________________________________________________________
____________________________________________________________
Note For more information about the DialogResult object, see the Visual
Studio .NET Help documentation.
4. Close the application, and then replace the "printDialog1.ShowDialog()"
code line in the PrintDoc procedure with the following lines of code.
DialogResult userResponse;
userResponse = printDialog1.ShowDialog();
if (userResponse == DialogResult.OK)
{
printDocument1.Print();
}
Module 6: Printing and Reporting in Windows Forms Applications
5. Run the PrintDialog application, and display the print dialog box.
6. Click OK, and then, inside in the Output File Name box, type C:\Text
7. Click OK.
Notice that a Printing dialog box opens automatically, providing the user
with an opportunity to cancel the print job.
8. Close the application, and close Visual Studio .NET.
31
32
Module 6: Printing and Reporting in Windows Forms Applications
Lesson: Constructing Print Document Content by Using
GDI+
„
What Is GDI+?
„
What Is the Graphics Object?
„
How to Create and Use Pens, Brushes, and
Fonts
„
How to Draw and Measure Text in the PrintPage
Event Procedure
„
How to Generate Print Content by Using
StreamReader
„
Demonstration: Constructing Print Document
Content by Using GDI+
„
Practice: Constructing Print Document Content
by Using GDI+
Introduction
In Windows Forms applications, you use GDI+ and the PrintPage event of the
PrintDocument object to construct the contents of a print document. This
lesson introduces GDI+ and covers how to use GDI+ methods to draw the text
and graphics content of a print document from in a .NET Windows Forms
application.
Lesson objectives
After completing this lesson, you will be able to:
„
Identify the components of GDI+ and use GDI+ in your applications.
„
Use a Graphics object as a canvas for creating the contents of a print
document.
„
Create and use the pens, brushes, and fonts that are required to draw text
and graphics objects.
„
Use the drawing methods of a Graphics object to draw text and twodimensional (2-D) vector graphics.
„
Generate print content by using StreamReader.
Module 6: Printing and Reporting in Windows Forms Applications
33
What Is GDI+?
„
„
GDI+ (the new graphics device interface)
z
Enables applications to generate graphics and
formatted text for the video display and the printer
z
Allows application developers to create deviceindependent applications
Three parts of GDI+
z
2-D vector graphics
z
Text
z
Images
Introduction
GDI+ is a graphics device interface that you can use to draw two-dimensional
vector graphics, text, and bitmapped images. GDI+ expands on the features of
GDI by providing new features such as gradient brushes and alpha blending.
GDI+ makes graphic programming easier and more flexible. It enables
applications to generate graphics and formatted text for the video display and
the printer. It also allows application developers to create device-independent
applications. For example, you can create a single PrintPage procedure to
construct graphical content that can be printed to most graphics printers or be
shown as a print preview on a graphics display screen.
Three parts of GDI+
The services of GDI+ fall into three main categories:
„
2-D vector graphics
Vector graphics involves drawing lines, curves, and figures that are defined
by a set of points on a coordinate system. GDI+ provides classes and
structures that store information about these objects. For example, the
Rectangle object stores information about the location and size of a
rectangle, and the Graphics class has methods for drawing lines, curves,
and other shapes.
„
Text
GDI+ allows you to draw text in a variety of fonts, sizes, and styles.
„
Images
Certain graphics cannot be displayed as 2-D vector graphics and must be
displayed as bitmaps. GDI+ provides the Bitmap class for displaying,
manipulating, and saving bitmaps. For more information about bitmaps, see
Appendix A, “Using Filled Shapes and Images,” in the student workbook.
34
Module 6: Printing and Reporting in Windows Forms Applications
What Is the Graphics Object?
„
Graphics Object:
z
z
z
Provides the drawing surface on which content is placed
Provides methods for drawing text and graphics at specified
locations
Provides various tools for modifying its contents
Graphics
Graphics myGraphic
myGraphic == this.CreateGraphics();
this.CreateGraphics();
'' draw
draw lines
lines or
or outlined
outlined shapes
shapes using
using aa Pen
Pen
myGraphic.Graphics.DrawLine(myPen,X1,Y1,X2,Y2)
myGraphic.Graphics.DrawLine(myPen,X1,Y1,X2,Y2) ;;
'' draw
draw filled
filled shapes
shapes using
using aa Brush
Brush
myGraphic.FillRectangle(myBrush,X1,Y1,X2,Y2);
myGraphic.FillRectangle(myBrush,X1,Y1,X2,Y2);
'' draw
draw text
text using
using aa Font
Font and
and aa Brush
Brush
myGraphic.DrawString(myText,myFont,myBrush,X1,Y1);
myGraphic.DrawString(myText,myFont,myBrush,X1,Y1);
Introduction
To draw the text, lines, and shapes that make up the content of a print
document, you must use a Graphics object.
Role of the Graphics
object in GDI+
The Graphics object is central to GDI+ and the construction of print document
content. It provides the drawing surface for the GDI+ drawing methods.
To construct print document content with GDI+:
Graphics object
methods
„
Set the properties of the Graphics object.
„
Call the methods of the Graphics object to draw text, lines, and shapes.
The Graphics object provides an extensive assortment of methods that can be
used to draw text, lines, and shapes. There are also methods for scaling,
transforming, and measuring the contents that have or will be drawn on its
surface. Some of the most common methods are listed in the following table.
Method
Description
Clear
Clears the entire drawing surface and fills it with the
specified background color.
DrawLine
Draws a line connecting the two points specified by
coordinate pairs.
DrawRectangle
Draws a rectangle specified by a coordinate pair, a width,
and a height.
DrawString
Draws the specified text string at the specified location
with the specified Brush and Font objects.
FillRectangle
Fills the interior of a rectangle.
MeasureString
Measures the specified string when drawn with the
specified font and formatted with the specified format.
Module 6: Printing and Reporting in Windows Forms Applications
Example
35
The following code examples show how to draw objects by using the Graphics
object provided by the PrintPageEventArgs parameter of the
PrintDocument.PrintPage event.
//Create a graphics object
Graphics myGraphics = this.CreateGraphics();
// draw lines or outlined shapes using a Pen
myGraphics.DrawLine(myPen,X1,Y1,X2,Y2) ;
myGraphics.DrawRectangle(myPen, X1, Y1, X2, Y2);
// draw filled shapes using a Brush
myGraphics.FillRectangle(myBrush,X1,Y1,X2,Y2);
// draw text using a Font and a Brush
myGraphics.DrawString(myText, myFont, myBrush, X1, Y1);
// measure text width on the Graphics object using a Font
textWidth = myGraphics.MeasureString(myText, myFont).Width;
36
Module 6: Printing and Reporting in Windows Forms Applications
How to Create and Use Pens, Brushes, and Fonts
Pens
A
A pen
pen is
is required
required to
to draw
draw lines
lines and
and outlined
outlined shapes
Pen
Pen myPen
myPen == new
new Pen(Color.Blue);
Pen(Color.Blue);
Brushes AA brush
brush is
is required
required to
to draw
draw filled
filled shapes
shapes or
or draw
draw text
text
SolidBrush
SolidBrush myBrush
myBrush == new
new SolidBrush(Color.Blue);
SolidBrush(Color.Blue);
Fonts
A
A font
font is
is required
required to
to draw
draw text
text of
of aa single
single size
size or
or style
style
Font
Font myFont
myFont == new
new Font("Arial",
Font("Arial", 12);
12);
Introduction
You use Pen, Brush, and Font objects to construct 2-D vector graphics, text,
and bitmap images with GDI+.
Procedure: Creating
pens
A pen is required to draw lines, curves, and outlined shapes. To create a new
pen, you must specify a color. You also have the option to specify values for
the width and line style properties:
1. Create a new pen.
Pen myPen = new Pen(Color.Blue);
2. Apply width and style properties.
The Width property for a Pen is of type Integer and has a default value of
1 (units are established by the Graphics object). The DashStyle property is
also of type Integer, but your code will be easier to read if you use the
DashStyle enumeration provided by the Drawing2D namespace. Although
the Width property can be set when you instantiate a new Pen, the line style
must be applied after the Pen has been created. The following code
examples demonstrate creating pens with various width and style properties.
Defaults are 1 for Width, and Style for Solid.
Pen penWideRed = new Pen(Color.Red, 10);
Pen penDashedBlack = new Pen(Color.Black, 6);
penDashedBlack.DashStyle = DashStyle.Dash;
penDashedBlack.DashCap = DashCap.Round;
Module 6: Printing and Reporting in Windows Forms Applications
Procedure: Creating
brushes
37
Brush objects are required for drawing text and filled shapes. You can create
brushes that produce Solid, Hatched, Textured, and Gradient fills.
• Create a new Brush.
The following code examples demonstrate creating a solid blue brush and a
linear gradient brush by using white and light blue blended horizontally.
Brush brushBlue = new SolidBrush(Color.Blue);
LinearGradientBrush myGrBrush = new LinearGradientBrush(
lgRectangle,
Color.White,
Color.LightBlue,
LinearGradientMode.Horizontal);
For more information about Hatched, Textured, and Gradient Brushes see
“Brushes and Filled Shapes” in the .NET Framework software development kit
(SDK) and see Appendix A, “Using Filled Shapes and Images,” in the student
workbook.
Procedure: Creating
fonts
Before you can draw text with GDI+, you must construct a Font object. The
declaration statement for a Font object can include parameters for the
FontFamily (such as Arial), Size, Style, and the GraphicsUnits used by the
Size parameter. The FontFamily and Size properties are required when creating
a new font.
• Create a new Font object.
The following code example creates an Arial font of size 10 and a Lucida
font with a style setting of bold and a size of 12 millimeters.
Font smallFont = new Font("Arial", 10);
Font largeFont;
largeFont = new Font("Lucida",
12,
FontStyle.Bold,
GraphicsUnit.Millimeter);
38
Module 6: Printing and Reporting in Windows Forms Applications
How to Draw and Measure Text in the PrintPage Event Procedure
„
To draw text
1. Calculate the location for the text
2. Select the Font and Brush that you want to use for this text
3. Call the Graphics.DrawString method
e.Graphics.DrawString(myText,
e.Graphics.DrawString(myText, myFont,
myFont, myBrush,
myBrush, X1,
X1, Y1);
Y1);
„
To measure text
textWidth
textWidth == e.Graphics.MeasureString(myText,myFont).Width;
e.Graphics.MeasureString(myText,myFont).Width;
textHeight
textHeight ==
e.Graphics.MeasureString(myText,myFont).Height;
e.Graphics.MeasureString(myText,myFont).Height;
Introduction
GDI+ enables you to draw and measure text.
You can draw text by using the DrawString method of the Graphics object. To
draw text, you must have a Brush object and a Font object.
If you need to determine the width or height of text as it will be drawn on the
page of a print document or another Graphics object, you can use the
MeasureString method of the Graphics object. For example, you must know
the width and length of a string as it appears on the page to center the string in a
region of the page. MeasureString can also be used to determine how many
lines of text will fit on a page, whether a line of text will fit between the
margins, and to right-align text.
Procedure: Drawing text
To construct text for your print document in the PrintPage event procedure:
1. Calculate the location on the page where the text will be placed.
2. Select the Font and Brush that you want to use for this text.
You can either use Fonts and Brushes that you already created or create
new ones. For more information about creating Fonts and Brushes, see the
topic How to Create and Use Pens, Brushes, and Fonts in this lesson.
3. Call the DrawString method.
To construct the text, call the DrawString method of the Graphics object.
e.Graphics.DrawString(myText, myFont, myBrush, X1, Y1);
Module 6: Printing and Reporting in Windows Forms Applications
Procedure: Measuring
text
To measure text, add the code as shown to the PrintPage event handler.
The following code measures the width and height of the specified string.
textWidth = e.Graphics.MeasureString(myText, myFont).Width;
textHeight = e.Graphics.MeasureString(myText,
myFont).Height;
Another option for getting the height of your text is to use the GetHeight
method for Font and pass it the Graphics object as follows.
textHeight = myFont.GetHeight(e.Graphics);
39
40
Module 6: Printing and Reporting in Windows Forms Applications
How to Generate Print Content by Using StreamReader
Use StreamReader to read lines of information from a
standard text file
private
private void
void btnPrintPreviewControl_Click(object
btnPrintPreviewControl_Click(object
sender,
sender, System.EventArgs
System.EventArgs e)
e)
{{
try
try
{{
StreamToPrint
StreamToPrint == new
new
StreamReader(“printMe.txt”);
StreamReader(“printMe.txt”);
try
try
{{
PrintPreview();
PrintPreview();
}}
finally
finally
{{
StreamToPrint.Close();
StreamToPrint.Close();
}}
}}
}}
Introduction
In addition to using GDI+ to generate print content, you can also use
StreamReader as an input provider. You use StreamReader to read lines of
information from a standard text file.
Example
The following example demonstrates how to use StreamReader with a
PrintPreviewControl. When the Print Preview button is clicked, the stream of
text is read from the file PrintMe.txt.
private void btnPrintPreviewControl_Click(
object sender, System.EventArgs e)
{
try
{
StreamToPrint = new StreamReader(FilePath);
try
{
PrintPreview();
}
finally
{
StreamToPrint.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Module 6: Printing and Reporting in Windows Forms Applications
41
The following code shows that if no text is being read from StreamReader, the
printing exits, or else it checks if there are more pages to print.
// inside PrintPage event handler
while (currentLine < linesPerPage)
{
textLine = StreamToPrint.ReadLine();
if(textLine == null)
{
break;
}
// position text, draw text, increment currentLine
}
//If more lines of text exist in the file, print another page.
if (TextLine != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
42
Module 6: Printing and Reporting in Windows Forms Applications
Demonstration: Constructing Print Document Content by Using
GDI+
In this demonstration, you see how to construct
print document content by using GDI+
Introduction
In this demonstration, you will see how to create print document content by
using GDI+.
Instructions
Ç Open the projects
1. Start two instances of Visual Studio .NET.
2. Open the PurchaseOrderApplication solution file in one instance of
Visual Studio .NET and the PrintingForm2555Class solution file in the
other. The solution files can be found under install_folder\Sampapps, in the
folders named OrderApplication and PrintingForm2555Class.
Ç Examine and modify code in the PrintingForm2555Class project
1. Open PrintingForm2555Class.cs in the Code Editor.
2. Mention that this class inherits from the PrintDocument class.
3. Describe the procedures that are used to: define the regions of the form,
draw the text, and 2-D vector objects that make up the blank form, receive
text content from the host application, and fill in the content on the form.
4. Move down to the PrintingEmptyForm2555 procedure, and then show the
code that is used to create the fonts and brushes for this document.
5. Scroll down and show some of the GDI+ code statements that draw the lines
and filled shapes.
6. Scroll down further and show the process required to center the purchase
item labels on the header row of the purchase item table.
7. Scroll back up to the top of this procedure and change some of the pen and
brush properties.
8. Rebuild the class.
Module 6: Printing and Reporting in Windows Forms Applications
43
Ç Examine and run the PurchaseOrderApplication project
1. Open MainForm.cs in the Code Editor.
2. Describe the procedures that are used to: read content from the form, pass
form content to the printing class, preview the print document, modify page
settings, and print the document.
3. In Solution Explorer, remove the reference to the PrintingForm2555Class
from the PurchaseOrderApplication project, and then add a reference to
the newly built class by browsing to the bin folder of the
PrintingForm2555Class folder and opening the PrintingFomr2555Class.dll
file.
4. Rebuild the PurchaseOrderApplication solution, and then run the
application.
5. Open the Print Preview dialog box to show your modifications.
44
Module 6: Printing and Reporting in Windows Forms Applications
Practice: Constructing Print Document Content by Using GDI+
In this practice, you will
z
Create pens, brushes, and fonts
z
Create 2-D vector objects
z
Measure and position text on the page
Begin reviewing the objectives
for this practice activity
15 min
Introduction
In this practice, you will construct print document content by using 2-D vectors
and text in GDI+.
Instructions
Ç Open the practice project
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_05\Starter.
2. Double-click the PrintPageCode.sln solution file to open the project.
Ç Create pens, brushes, and fonts
1. Open Form1 in the Code Editor.
2. On the View menu, point to Show Tasks, and then click Comment.
3. In the Task List, double-click TODO: create pens.
4. Add the following code statements below the TODO line.
Pen penWideRed = new Pen(Color.Red, 10);
Pen penDashedBlack = new Pen(Color.Black, 6);
penDashedBlack.DashStyle = DashStyle.Dash;
penDashedBlack.DashCap = DashCap.Round;
5. In the Task List, double-click TODO: create brushes.
6. Add the following code statements below the TODO line.
Brush brushBlue = new SolidBrush(Color.Blue);
Brush brushBlack = Brushes.Black;
7. In the Task List, double-click TODO: create fonts.
Module 6: Printing and Reporting in Windows Forms Applications
45
8. Add the following code statements below the TODO line.
Font fontMedium = new Font("Arial", 14);
Font fontLargeBold;
fontLargeBold = new Font("Arial", 36, FontStyle.Bold);
9. Do any of the code statements that you entered require a reference to the
Drawing2D namespace?
Yes. The code statements used to set the DashStyle and DashCap use
enumerations provided by the Drawing2D namespace.
____________________________________________________________
____________________________________________________________
Ç Create 2-D vector objects
1. In the Task List, double-click TODO: draw outline shapes.
2. Add the following code statements below the TODO line.
e.Graphics.DrawLine(penWideRed,
hPos1,
vPos1,
hPos2,
vPos2);
e.Graphics.DrawRectangle(penDashedBlack,
hPos1,
vPos1,
rectWidth,
rectHeight);
3. In the Task List, double-click TODO: draw filled shapes.
4. Add the following code statements below the TODO line.
Rectangle fillRectangle;
fillRectangle = new Rectangle(
lgRectangle.Left,
lgRectangle.Bottom,
lgRectangle.Width,
lgRectangle.Height);
e.Graphics.FillRectangle(brushBlue, fillRectangle);
Ç Measure and position text on the page
1. In the Task List, double-click TODO: draw centered text.
2. Add the following code statements below the TODO line.
textWidth = e.Graphics.MeasureString(centeredText,
fontMedium).Width;
textHeight = fontMedium.GetHeight(e.Graphics);
hPos = rectText.Left + (rectText.Width - textWidth) / 2;
vPos = rectText.Top + (rectText.Height - textHeight) / 2;
e.Graphics.DrawRectangle(Pens.Black, rectText);
e.Graphics.DrawString(centeredText,
fontMedium,
brushBlack,
hPos,
vPos);
46
Module 6: Printing and Reporting in Windows Forms Applications
3. Run your application, and click Print Preview to view the GDI+ output.
4. Close the preview form, click Draw gradient text, and then click Print
Preview.
5. How would you draw right-aligned text?
You can draw right-aligned text by measuring the text string and
establishing a horizontal position that is equal to the right-side position
that you define minus the width of the text string.
____________________________________________________________
____________________________________________________________
If time permits, examine the code used to create the gradient filled text.
6. Save your application, and then close Visual Studio .NET.
Module 6: Printing and Reporting in Windows Forms Applications
47
Lesson: Creating Reports by Using Crystal Reports
Introduction
„
Crystal Reports
„
How to Create and Format a Report by Using Crystal
Reports
„
How to View a Report by Using Crystal Report Viewer
„
How to Add DataSets to a Report
„
Practice: Creating and Viewing Crystal Reports
There are many ways to present data to users. For example, you could write
code to loop through recordsets and print them inside your Windows-based
application. However, by using such methods, any work beyond basic
formatting can be complicated and difficult to program.
With Crystal Reports for Microsoft Visual Studio .NET, you can quickly create
complex and professional-looking reports. Instead of writing code, you use the
Crystal Report Designer interface to create and format the report that you need.
The powerful Report Engine processes the formatting, grouping, and charting
criteria that you specify.
This lesson introduces Crystal Reports for Visual Studio .NET and also covers
how to use Report Expert to create and format reports.
Lesson objectives
After completing this lesson, you will be able to:
„
Explain how Crystal Reports helps in creating reports.
„
Create and format a report by using Crystal Reports.
„
View a report by using Crystal Report Viewer.
„
Add datasets to a report.
48
Module 6: Printing and Reporting in Windows Forms Applications
Crystal Reports
Crystal Reports
y Is the standard reporting tool in .NET
y Allows you to create a report from the beginning or use
one of the Report Expert Wizards
Benefits
y You can use any programming language
y Report viewers for Windows-based and Web applications
y Run time customization of reports
y Easy interaction with reports
y Data visualization and analysis capabilities
http://msdn.microsoft.com/vstudio/partners/tools
/crystaldecisions.asp
Introduction
Crystal Reports is the standard reporting tool in Visual Studio .NET. It allows
you to create a report from scratch or use one of the Report Expert Wizards.
Before you learn how to use Crystal Reports for creating and formatting
reports, you must understand the benefits of using Crystal Reports.
Benefits of using Crystal
Reports
Crystal Reports:
„
Allows you to choose the language and project.
Use the programming language of your choice and access Crystal Report
Designer from any project.
„
Provides report viewers for Windows-based and Web applications.
Crystal Reports provides two report viewers that you can use to view your
report in your application: Web Forms Viewer for Web applications and
Windows Forms Viewer for Windows-based applications.
„
Allows run-time customization of reports.
Crystal Reports enables the viewer to interact with other controls at run
time. With run-time customization, users can view different reports or
change the format, data selection, or export options of an existing report.
„
Allows users to interact easily with reports.
Because Crystal Reports can interact with other controls, users are able to
filter report information by clicking a button or selecting from a combo box.
„
Provides data-visualization and analysis capabilities.
Crystal Reports provides developers with data visualization and analysis
capabilities. It uses an open and flexible architecture—with standards like
extensible markup language (XML)—to allow you to share reports and
information over the Web. It also offers features such as details on charts,
report navigation, and text search.
Module 6: Printing and Reporting in Windows Forms Applications
How to Create and Format a Report by Using Crystal Reports
Open
Open the
the
Report
Report
Expert
Expert
Choose
Choose a
a
template
template
Choose a
data source
Creating a Crystal Report by
Using the Report Expert
Format
Format
the
the report
report
Generate
Generate
a
a report
report
Select
Select the
the
required
required
fields
fields
Group items
and create
formulas
Introduction
You can use Crystal Reports to add reporting capabilities to your application.
Crystal Reports allows you to create a report from the beginning or use the
Report Expert, which helps you create a report by using a wizard.
Procedure: Create and
format a report by using
Report Expert
To create and format reports by using the Report Expert:
1. Open Report Expert.
a. In Solution Explorer, right-click the project name, point to Add, and
then select Add New Item from the shortcut menu.
b. In the Add New Item dialog box, in the Templates pane, click Crystal
Report.
c. In the Name box, type a report name with an .rpt extension.
d. Click Open to invoke Crystal Report Designer, which will help you
create and design the new report.
e. In Crystal Report Gallery, select the Using the Report Expert option.
49
50
Module 6: Printing and Reporting in Windows Forms Applications
2. Choose a template.
Report Expert provides various templates for creating a report. Some of the
templates are:
• Standard
• Form Letter
• Form
• Cross-Tab
• Subreport
• Mail Label
• Drill Down
• For more information about each of the templates, in the
Visual Studio .NET Help documentation, search by using the phrase
Crystal Reports Experts.
3. Choose a data source.
Select the data source that your report will reference. You can use more than
one data source in a report. You also choose the database tables that you
want to use in the report. Crystal Reports can automatically link the tables,
or you can specify how you want the tables linked. Database tables are
linked so that records from one database match related records from
another.
4. Select the required fields.
After selecting the data source, select the fields that you want to display on
the report.
5. Group items and create formulas.
When you first insert a database field into your report, the data in the fields
appears in the order in which it was originally entered into the database.
Grouping, sorting, and totaling help turn disorganized data into useful
information on a report.
In most cases, the data needed for a report already exists in database table
fields. Sometimes, you need to put additional data on the report that does
not exist in any of the data fields. In cases such as this, you must create a
formula. There are four different groups of formulas in Crystal Reports:
report, conditional formatting, selection, and search. The majority of
formulas in a report use the report and conditional formatting formulas.
For more information about how to create and use these formulas, in the
Visual Studio .NET Help documentation, search by using the phrase
Formula Overview.
Module 6: Printing and Reporting in Windows Forms Applications
51
6. Generate the report.
After you have added the required fields and formulas to the report, click
Finish to generate the report.
7. Format the report.
After a report is generated, you might want to make changes to the layout
and design of the report, as well as the appearance of text, objects, or entire
report sections. You can use various formatting options to change the layout
of your reports.
• To format an object, right-click the object, and then click Format.
• To format a report section, right-click the report section, and then click
Format Section.
52
Module 6: Printing and Reporting in Windows Forms Applications
How to View a Report by Using Crystal Report Viewer
To View a Report by Using Crystal Report Viewer
Add the Crystal Report Viewer control to the form
Set ReportSource to the name of the report that is displayed
Use ShowZoomButton to zoom in and zoom out on the report
Use ShowPrintButton to print the report
Introduction
Visual Studio .NET includes a Crystal Report Viewer control that enables you
to view a report at run time. To specify the report that you want to view, you set
the ReportSource property of the viewer.
Procedure: Viewing a
report
To view a report by using the Crystal Report Viewer control:
1. Add a Crystal Report Viewer control to the form.
The Controls Toolbox includes the Crystal Report Viewer control. To add
the control to the form, drag the control from the Toolbox to the form.
2. Set the ReportSource property of the viewer.
The next step is to set the ReportSource property of the Crystal Report
viewer to the name of the report that is to be displayed. You can set the
ReportSource property in the Properties window at design time or you can
set it at run time.
3. Use the ShowZoomButton property to zoom in or zoom out on reports.
The Crystal Report viewer includes the ShowZoomButton to zoom in or
zoom out on reports. To enable this property, set the ShowZoomButton
property to True in the Properties window.
4. Use the ShowPrintButton property to print the report.
The ShowPrintButton property enables you to print the report. Set the
ShowPrintButton property to True to enable the button on the viewer.
Module 6: Printing and Reporting in Windows Forms Applications
53
How to Add DataSets to a Report
„
Adding datasets to reports allows you to create
reports that are disconnected from the database
„
To add datasets to a report, add the code to the
Form_Load event
private
private CrystalReport.StoreSalesReport
CrystalReport.StoreSalesReport report;
report;
storeSalesSqlDataAdapter.Fill(storeSalesDataSet1);
storeSalesSqlDataAdapter.Fill(storeSalesDataSet1);
report
report == new
new CrystalReport.StoreSalesReport();
CrystalReport.StoreSalesReport();
report.SetDataSource(storeSalesDataSet1);
report.SetDataSource(storeSalesDataSet1);
crystalReportViewer1.ReportSource
crystalReportViewer1.ReportSource == report;
report;
Introduction
Crystal Reports for Visual Studio .NET supports reports that access ADO.NET
datasets.
Procedure: Adding an
ADO.NET dataset to a
report
To add an ADO.NET dataset to a report:
1. Create an instance of the report.
To make the report display the data at run time, you must first create an
instance of the report:
private CrystalReport.StoreSalesReport report;
report = new CrystalReport.StoreSalesReport();
2. Generate a design time instance of a dataset.
The design time instance of the dataset exposes the fields in the dataset to
Report Expert. The design time dataset contains only the data description,
and not the actual data. Therefore, when working with a report connected to
a dataset object, you cannot browse field data in Crystal Report Designer at
design time.
3. Populate the dataset.
storeSalesSqlDataAdapter.Fill(storeSalesDataSet1);
4. Call the SetDataSource method of the report, and pass an instance of the
populated dataset.
report.SetDataSource(StoreDataSet1);
5. Set the ReportSource property of the Crystal Report Viewer to the instance
of the report.
crystalReportViewer1.ReportSource = report;
54
Module 6: Printing and Reporting in Windows Forms Applications
Practice: Creating and Viewing Crystal Reports
In this practice, you will
z
Configure the SqlConnection1 control on
Form1 to connect to the pubs database
z
Create a Crystal Report
z
Add a Crystal Report Viewer control to
Form1
Begin reviewing the objectives for
this practice activity
Introduction
In this practice, you will create and view Crystal Reports.
Instructions
Ç Open the practice project
12 min
1. Use Windows Explorer to browse to
install_folder\Practices\Mod06\Mod06_06\Starter.
2. Double-click the CrystalReport.sln solution file to open the project.
Ç Configure the sqlConnection1 control on Form1 to connect to the Pubs
database
1. Open Form1 in Design view.
2. Select sqlConnection1, and from the Properties window, click the
ConnectionString property, click the arrow, and then click New
Connection.
Note Use the existing connection information for the Pubs database if it
already exists and skip to the next procedure.
3. In the Data Link Properties dialog box, type computername\MOC where
computername is the name of your computer.
4. Select the Use Windows NT Integrated Security option.
5. Select the Pubs database from the drop-down list, click Test Connection to
ensure that you can access the Pubs database, click OK, and then click OK
again.
Module 6: Printing and Reporting in Windows Forms Applications
55
Ç Create a Crystal Report
1. On the File menu, click Add New Item.
2. On the Add New Item dialog box, under Template, click Crystal Report.
3. Set the name of the report to StoreSalesReport.rpt, and then click Open.
4. Close the Crystal Decisions Registration Wizard dialog box.
5. On the Crystal Report Gallery dialog box, click OK.
6. On the Data tab, expand Project Data, expand ADO.NET DataSets, and
then expand CrystalReport.storeSalesDataSet.
7. Click Insert Table, and then click Next.
8. On the Fields tab, in Available Fields list, click stor_id, and then click Add.
9. Repeat step 8 to add all of the fields that are listed below stores table in the
Available Fields list, and then click Next.
10. On the Group tab, in the Available Fields list, below Report Fields, click
stores.stor_name, click Add, and then click Next.
11. On the Total tab, in the Summarized Fields list, click stores.qty, click
Remove, and then click the Style tab.
12. Set the title to Store Sales, and then click Finish.
Ç Add a Crystal Report Viewer control to Form1
1. Open Form1 in Design view.
2. In the Toolbox, double-click CrystalReportViewer.
3. Set the Dock property of the CrystalReportViewer so that the control fills
the entire form.
4. Open Form1 in the Code Editor.
5. On the View menu, point to Show Tasks, and then click Comment.
6. In the Task List, double-click TODO 1: create an instance of
StoreSalesReport.
7. Add the following code statement below the TODO line:
private CrystalReport.StoreSalesReport report;
8. In the Task List, double-click TODO 2: Call the SetDataSource method
of report and pass storeSalesDataSet1.
9. Add the following code statements below the TODO line:
report = new CrystalReport.StoreSalesReport();
report.SetDataSource(storeSalesDataSet1);
crystalReportViewer1.ReportSource = report;
10. Build and run your application.
11. Use the Crystal Report Viewer control to examine your report.
Notice the features provided on the viewer’s toolbar.
12. Save your project, and then close Visual Studio .NET.
56
Module 6: Printing and Reporting in Windows Forms Applications
Review
„
Printing from a Windows Forms Application
„
Using the Print Preview, Page Setup, and Print Dialogs
„
Constructing Print Document Content by Using GDI+
„
Creating Reports by Using Crystal Reports
1. List the tasks involved in printing simple text file output in
Visual Studio .NET.
Use a StreamReader object to read in the contents of the text file and
then draw the contents of the StreamReader line-by-line onto the
Graphics object inside your PrintDocument.PrintPage event handler.
The Graphics object is supplied by the PrintPageEventArgs class,
which is the event arguments parameter (e) for the PrintPage event
handler.
2. What property is used to capture user input from a dialog box?
The DialogResult property of the parent form is used to capture the
action taken to close a dialog box. For example, DialogResult can be
used to determine whether the PrintDialog was closed by clicking OK
or by clicking Cancel.
3. What is the role of the Graphics object in printing by using GDI+?
The Graphics object acts as the canvas on which the GDI+ methods
draw.
4. What methods of GDI+ are used to draw text and graphics?
Methods such as DrawRectangle and FillEllipse are used to draw 2-D
vector shapes. The DrawString method is used to draw text.
Module 6: Printing and Reporting in Windows Forms Applications
57
5. What kind of object does the following code create?
Pen myPen = new Pen(Color.Black);
Graphics g = this.CreateGraphics();
g.DrawEllipse(myPen, 20, 30, 10, 50);
This Visual C# .NET code produces the 2-D vector outline shape of an
ellipse by using a solid black pen that has the default width of 1 pixel
(the default graphic unit).
6. List some of the benefits of using Crystal Reports.
Crystal Reports provides a fast and easy way to generate professional
looking reports.
7. List the steps involved in creating a report by using Crystal Reports.
Establish the database connection to your data, add a Crystal Report
(.rpt file) to your project, configure the report by using the Crystal
Report Gallery, add a CrystalReportViewer control to your form,
declare a report object and assign an instance of your report (.rpt) to it,
use the SetDataSource property of your report object to populate it
with data, and then assign the report object to the ReportSource
property of your CrystalReportViewer.
58
Module 6: Printing and Reporting in Windows Forms Applications
Lab 6.1: Printing Formatted Documents
Objectives
„
Exercise 1: Adding Print Support to an
Application
„
Exercise 2: Creating Printed Output by Using
GDI+
After completing this lab, you will have demonstrated your ability to:
„
Reference a namespace so that you don’t have to fully qualify each
namespace member in your code.
„
Use the PrintDocument class and the PrintPage event to enable printing in
a Windows Forms application.
„
Use the PageSetupDialog, PrintPreviewDialog, and PrintDialog classes
to provide user control over the print process.
„
Create pens, brushes, and fonts for use with GDI+ drawing methods.
„
Use GDI+ methods to draw outline and filled shapes on a print document.
„
Measure and position text on a print document.
Note This lab focuses on the concepts in Module 6, “Printing and Reporting in
Windows Forms Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET). As a result, this lab may not
comply with Microsoft security recommendations.
Prerequisites
Before working on this lab, you must have:
„
The knowledge and skills to develop a simple Windows Forms application
by using a Visual Studio .NET–compatible programming language.
„
The knowledge and skills to use elements of the System.Drawing
namespace and the PrintDocument class in a Visual Studio .NET–based
application.
„
The knowledge and skills to use the PrintPreviewDialog,
PageSetupDialog, and PrintDialog classes in a Visual Studio .NET–based
application to provide user control of the print process.
„
The knowledge and skills to use the two-dimensional (2-D) vector and Text
drawing capabilities of GDI+ in a Visual Studio .NET–based application.
Module 6: Printing and Reporting in Windows Forms Applications
Scenario
Members of the Northwind Traders sales force need to print purchase order
documents while they are at a customer site. The purchase order documents—
form number NT-2555P (portrait) and NT-2555L (landscape)—have specific
requirements associated with document layout, text formatting, and the
appearance of 2-D vector graphics objects. You are an application developer at
Northwind Traders. The department that you work in is developing a purchase
order application that will be used by the Northwind Traders sales force. You
have been assigned the task of completing the code sections of the purchase
order application that support printing. The Northwind Traders Legal and
Media departments have given you the three requirements tables that describe
these forms. The tables are included at the end of this lab.
To complete this task, you must add basic print support to a project, enable
users to control the print process by using dialog boxes, and develop the code
statements necessary to complete the construction of the print document by
using GDI+.
Estimated time to
complete this lab:
60 minutes
59
60
Module 6: Printing and Reporting in Windows Forms Applications
Exercise 1
Adding Print Support to an Application
In this exercise, you will open two existing Visual Studio .NET projects, create a reference to the
Drawing and Drawing2D namespaces, create a procedure that handles the PrintPage event,
develop code that ensures that all pages of a print document are included in a print job, and add
support for the PrintPreviewDialog, PageSetupDialog, and PrintDialog dialog boxes to your
application. This exercise assesses your knowledge of the print process and your ability to use the
PrintDocument class and the three dialog boxes to provide the application user with control of the
print process.
There are starter and solution files associated with this exercise. Browse to
install_folder\Labfiles\Lab06_1\Ex01\Starter to find the starter files, and browse to
install_folder\Labfiles\Lab06_1\Ex01\Solution to find the solution files. If you performed a default
installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555.
Scenario
The user interface of the purchase order application has been developed and the underlying code is
functioning as intended. You have reviewed the application code and the code contained in a
custom document printing class that inherits from the PrintDocument class. The custom printing
class that your department created will be used to print the purchase order forms that are used by
Northwind Traders. Most of the code that is used to construct (draw) purchase order documents has
already been written. You will now begin adding code to your application and the printing class so
that users can print purchase order documents.
The Northwind Traders sales force has requested that the application be capable of printing in either
portrait or landscape mode and that page margins be fixed in accordance with the Legal department
and Media department requirements for the purchase order document. The sales force would also
like to have the option to review the purchase order document with a customer before it is printed.
As the application developer, you will start by opening the purchase order application and the
printing class in separate projects and checking to see what code still needs to be added to the two
projects to support document printing. Then, you will add support for the PrintPreviewDialog. In
addition to providing the sales force with an easy way to preview a purchase order before printing,
the PrintPreview dialog box enables you to view the print document as you develop the code that
constructs the document. You will then add support for the PageSetupDialog class to your
application and create the code that is required to show this dialog box. By checking various page
layout settings, you can ensure that the print document is constructed in accordance with the page
layout parameters needed by your Legal and Media departments. Because your customer also wants
the option to print without previewing the document, you will also add support for the PrintDialog
class.
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
1.
Open two instances of
Visual Studio .NET. In the
first instance, open the
Lab06Application.sln file.
In the second instance, open
the Lab06Class.sln file. To
open the solution files, in
the Lab06Application and
Lab06Class folders,
respectively, browse to
install_folder\Labfiles\
Lab06_1\Ex01\Starter.
61
Additional information
a.
For more information about opening a project file and starting an
application, see the following resource:
•
The Visual Studio .NET Help documentation. For additional
information about opening a project file, in Search, select the
Search in titles only check box, then search by using the phrase
Open Project Dialog Box. For additional information about
starting an application from in Designer, in Index, search by using
the phrase Debugging Windows Applications.
You can open two instances
of Visual Studio .NET when
you want to work on an
application and an external
class library at the same
time.
2.
Use the Task List in the
Lab06Class.cs file to locate
the code section 'TODO:
Programmatically reference
required namespaces' and
then add code statements
that reference the Drawing
and Drawing2D
namespaces.
When you create a reference
to a namespace, you can
refer to the namespace
members without having to
fully qualify member names
in your code. This makes
your code easier to develop
and easier to read.
a.
For more information about the Drawing and Drawing2D namespaces
and why you should use them, see the following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. For additional
information about creating a reference to a namespace, search by
using the phrases References and the Imports Statement,
Namespaces and Imports Statement. For additional information
about the Drawing and Drawing2D namespaces, search by using
the phrases System.Drawing and System.Drawing.Drawing2D.
62
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
3.
Use the Task List in the
Lab06Class.cs file to locate
the code section 'TODO:
Create the declaration
statement for the PrintPage
Procedure' and then create
the declaration statement for
a procedure named
Lab06Class_PrintPage that
handles the PrintPage
event. Add code statements
to the procedure that call the
PrintingEmptyForm2555
and PrintingContentsForm
2555 procedures.
Additional information
a.
For more information about the PrintPage event and the
PrintPageEventArgs class, see the following resources:
•
Lesson: Printing From a Windows Forms Application in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
Practice: Adding Print Support to a Windows Forms Application in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. For additional
information about the PrintPage event, search by using the phrases
Creating Standard Windows Forms Print Jobs and
PrintDocument.PrintPage Event. For additional information
about the PrintPageEventArgs class, search by using the phrases
PrintPageEventArgs Class and PrintPageEventArgs Members.
The PrintPage procedure
handles all requests for a
page of the print document.
The PrintPageEventArgs
class that is passed to the
PrintPage procedure
contains the Graphics
object on which you
construct the print
document.
4.
Use the Task List in the
Lab06Class.cs file to locate
the code section 'TODO:
Determine if more pages
must be printed' and then
create a code section that
tells the event handler for
the PrintPage event that
there are more pages to print
when currentPurchaseItem
Number is less than
totalPurchaseItems,
otherwise specify that there
are no more pages to print.
In Visual Studio .NET, you
must create your own
programming logic to set the
HasMorePages property to
generate print documents
that consist of more than one
page.
a.
For more information about how to specify that there are additional
pages to be printed, see the following resources:
•
Lesson: Printing From a Windows Forms Application in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
Practice: Adding Print Support to a Windows Forms Application in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase PrintPageEventArgs.HasMorePages Property.
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
5.
Rebuild the Lab06Class
project. In the
Lab06Application project, in
Solution Explorer, update
the reference to Lab06Class.
63
Additional information
a.
For more information about referencing an external class, see the
following resource:
•
The Visual Studio .NET Help documentation. Search by using the
phrases Project References, Adding and Removing References,
and Preparing and Managing Builds.
After you rebuild a class
library, ensure that your
applications reference the
new version.
6.
Open the code editor view
of MainForm.cs in the
Lab06Application project,
and configure the Task List
to display comments.
a.
For more information about the code editor view and the Task List, see
the following resource:
•
Using the Task List and
TODO comments can help
you remember development
tasks that must still be done.
7.
Use the Task List to locate
the code section 'TODO:
Create an instance of the
PrintPreviewDialog class'.
Add code below the
comment line that creates an
instance of the
PrintPreviewDialog class
named
form2555PreviewDialog.
a.
The Visual Studio .NET Help documentation. For help with the
code editor, search by using the phrase Managing the Code
Editor and View. For help with Task List, search by using the
phrase Task List Views.
For more information about the PrintPreviewDialog class and how to
add an instance of this dialog box to your application, see the following
resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PrintPreviewDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase Introduction to the Windows Forms PrintPreviewDialog
Control.
64
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
8.
Use the Task List to locate
the code section 'TODO:
Create an instance of the
PageSetupDialog class'.
Add code below the
comment line that creates an
instance of the
PageSetupDialog class
named
form2555SetupDialog.
Additional information
a.
The PageSetupDialog class
enables users to modify the
page settings of a print
document. You can use it to
test the code that constructs
the print document by
displaying the print
document with various page
setting values. You will get
a chance to modify page
settings later in this lab
exercise.
9.
Use the Task List to locate
the code section 'TODO:
Create an instance of the
PrintDialog class'. Add code
below the comment line that
creates an instance of the
PrintDialog class named
form2555PrintDialog.
a.
For more information about adding the PageSetupDialog class to an
application, see the following resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PageSetupDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Introduction to the Windows Forms PageSetupDialog
Component, PageSetupDialog Class, and PageSetupDialog
Members.
For more information about adding support for the PrintDialog class to
your application, see the following resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PageSetupDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Introduction to the Windows Forms PrintDialog
Component and PrintDialog Component.
Module 6: Printing and Reporting in Windows Forms Applications
65
Tasks
Additional information
10. Use the Task List to locate
a.
The purchaseItemNumber and purchaseItemCount variables are passed
to the Lab06Class class (inherits from PrintDocument) and used to
determine when HasMorePages should be set to True or False. The
purchaseItemNumber variable is the current purchase item being
printed, and the purchaseItemCount variable is the total number of
purchase items in the current purchase order.
a.
For more information about the PrintPreviewDialog class and how it
can be used in the print process, see the following resources:
the code section 'TODO: Set
purchaseItemNumber and
purchaseItemCount'. Add
code below the TODO
comment that assigns a
value of 0 to the
MainModule.purchaseItem
Number variable and assigns
the value of the Count
property of
MainModule.mainPOForm.
ProductOrderPanel.Controls
to the
MainModule.purchaseItem
Count variable.
In addition to developing the
code logic that determines
when HasMorePages is
True or False, you must
reset the variables that are
used to make this
determination every time a
print document is generated.
11. Use the Task List to locate
the code section 'TODO:
Add support for a full screen
preview of the print
document'. Add code below
the comment line that
assigns the
form2555Document
instance of the Lab06Class
class to the Document
property of
form2555PreviewDialog
(the print preview dialog
box) and displays the print
document by using the full
display screen.
Implementing support for
the print preview dialog box
early in the development
process enables you to
preview the print document
as you develop the code that
constructs your document.
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PrintPreviewDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase Displaying Print Preview in Windows Applications.
66
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
Additional information
12. Rebuild and then start the
a.
Lab06Application project.
Use the File menu or the
Print button on the ToolBar
control to demonstrate that
you can now display the
print preview dialog box.
Close the Lab06Application
executable file.
For more information about building and debugging your applications,
and for information about running the Purchase Order application, see
the following resources:
•
Demonstration, Purchase Order Application, in Module 0,
“Introduction,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Default and Custom Builds and Using the Debugger.
You can use the Print
Preview dialog box to
verify that the code in your
PrintPage procedure is
working correctly. Try
adding 25 purchase items to
a purchase order. The print
document should now wrap
onto a second page when
previewed.
13. Use the Task List to locate
the code section 'TODO:
Apply the initial page
settings'. Add code below
the comment line that
assigns the
form2555PageSettings
variable to the PageSettings
property of the Page Setup
dialog box that you
instantiated.
The page setup dialog box
must be assigned an initial
PageSettings value before it
can be displayed for the first
time; otherwise, an error
will occur.
a.
The form2555PageSettings object is scoped at the module level so
that user-specified settings are maintained between viewings of the
PageSetupDialog class.
b. For more information about the PageSettings class, see the following
resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PageSetupDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase PageSettings Class.
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
Additional information
14. Use Task List to locate the
a.
code section 'TODO:
Disable user access to the
Margins section of the
dialog'. Add code below the
comment line that disables
user access to the margin
settings.
Restricting user access to
only those page settings that
are required will help to
eliminate support issues that
would be generated when
users modify settings in an
unpredictable manner.
15. Rebuild and then start the
a.
Lab06Application project.
Use the File menu to open
the page setup dialog box
and change the page
orientation from portrait to
landscape. Use the print
preview dialog box to view
the print document. Close
the Lab06Application
executable file.
16. Use the Task List to locate
the code section 'TODO:
Determine if the document
should be printed'. Add code
statements below the
comment line that will send
form2555Document to the
printer when the application
user clicks OK to close the
print dialog.
You must use DialogResult
to determine whether the
user closed PrintDialog by
clicking Cancel or by
clicking OK.
For more information about members of the PageSetupDialog class,
see the following resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PageSetupDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase PageSetupDialog Members.
For more information about building and debugging your application,
use the following resource:
•
a.
67
The Visual Studio .NET Help documentation. Search by using the
phrases Default and Custom Builds and Using the Debugger.
For more information about using DialogResult, see the following
resources:
•
Lesson: Using the Print Preview, Page Setup, and Print Dialogs in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: Using the PageSetupDialog Control in Module 6,
“Printing and Reporting in Windows Forms Applications,” in
Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrase Retrieving the Result for Dialog Boxes.
68
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
Additional information
17. Rebuild and then start the
a.
Lab06Application project.
Use the File menu to
demonstrate that the print
dialog box is working as
intended. Close the
Lab06Application
executable file.
18. Save the changes that you
made to your code, and then
close both solution files.
For more information about building and debugging your application,
see the following resource:
•
The Visual Studio .NET Help documentation. Search by using the
phrases Default and Custom Builds and Using the Debugger.
Additional information is not necessary for this task.
Module 6: Printing and Reporting in Windows Forms Applications
69
Exercise 2
Creating Printed Output by Using GDI+
In this exercise, you will create pens, brushes, and fonts and then use them to draw 2-D vector
objects and text at specific locations on a print document. This exercise provides you with an
opportunity to assess your ability to complete the construction of a print document by using GDI+.
There are starter and solution files associated with this exercise. Browse to
install_folder\Labfiles\Lab06_1\Ex02\Starter to find the starter files, and browse to
install_folder\Labfiles\Lab06_1\Ex02\Solution to find the solution files. If you performed a default
installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555.
Scenario
Initial testing has revealed that the custom printing class does not accurately reproduce the legal and
official representation of the organization’s purchase order documents—Northwind Traders forms
NT-2555P and NT-2555L. To correct this problem, you will review the data contained in the
NT-2555P and NT-2555L requirements tables (the tables of data from the Media and Legal
Departments that are included after this exercise) and develop GDI+ code statements that produce
the required 2-D vector objects and text. You will begin by creating some of the pens, brushes, and
fonts required to construct portions of the forms. After that, you will develop the code that draws
some of the 2D vector shapes that are used to create the base forms. The last step will be to develop
the code used to draw some of the text that appears on the NT-2555P and NT-2555L forms.
Tasks
1.
2.
Additional information
In the first instance of
Visual Studio .NET, browse
to install_folder\Labfiles\
Lab06_1\Ex02\Starter and
open the
Lab06Application.sln file.
In the second instance,
browse to
install_folder\Labfiles\
Lab06_1\Ex02\Starter and
open the Lab06Class.sln
file.
a.
Open the code editor view
of the Lab06Class.cs file
and use Task List to locate
the code section 'TODO:
Create the pageBorderPen'.
Add code below the
comment line that creates a
pen named pageBorderPen
and that has the following
characteristics:
Color = Gray,
width = 3,
DashStyle = Dash.
a.
For more information about opening a project file and starting an
application, see the following resources:
•
The Visual Studio .NET Help documentation. For additional
information about opening a project file, in Search, select the
Search in titles only check box, then search by using the phrase
Open Project Dialog Box. For additional information about
starting an application from in Designer, in Index, search by using
the phrase Debugging Windows Applications.
For more information about creating pens, see the following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Pens, Brushes, and Colors; Setting Pen Width and
Alignment (in the .NET Framework Developer’s Guide) and
Using a Brush to Fill Shapes.
70
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
3.
4.
Use the Task List to locate
the code section 'TODO:
Create the footerBrush'. Add
code below the comment
line that creates a solid black
brush named footerBrush.
Use the Task List to locate
the code section 'TODO:
Create the footerFont'. Add
code below the comment
line that creates a Private
font named footerFont and
that has the following
characteristics: family =
Microsoft Sans Serif,
emSize = 7.
Additional information
a.
a.
For more information about creating brushes, see the following
resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Pens, Brushes, and Colors; Setting Pen Width and
Alignment and Using a Brush to Fill Shapes.
For more information about creating fonts, see the following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Constructing Font Families and Fonts (in the .NET
Framework Developer’s Guide), Fonts and Text (in the .NET
Framework Developer’s Guide), and Using GDI+ Managed
Classes (in the .NET Framework Developer’s Guide).
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
5.
Use the Task List to locate
the code section 'TODO:
Draw the border of the
Customer Address table'.
Create the code statements
required to draw the border
of the customer address
table by using the following
variables:
sectionOutlinePen,
customerSectionLeft,
customerSectionTop,
customerSectionWidth,
customerSectionHeight.
71
Additional information
a.
For more information about drawing 2-D vector shapes, see the
following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Pens, Lines, and Rectangles; Using a Pen to Draw Lines
and Rectangles; and Graphics Methods.
GDI+ offers many ways to
draw an outlined shape such
as a rectangle. As a
developer, it is important to
consider whether the
parameters used to draw a
shape can be used again
later in your program before
you select a drawing
method.
6.
Use the Task List to locate
the code section TODO:
Draw a rectangle that
defines the margin limits'.
Create the code statements
required to draw a rectangle
that defines the limits of the
page by using the following
variables: pageBorderPen,
pageLeft, pageTop,
pageWidth, pageHeight.
a.
For more information about drawing 2-D vector shapes, see the
following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Pens, Lines, and Rectangles; Using a Pen to Draw Lines
and Rectangles; and Graphics Methods.
72
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
7.
Use the Task List to locate
the code section 'TODO:
Draw the shaded area of the
Purchase Items table'.
Create the code statements
required to draw the shaded
portion of the Purchase
Items table by using the
following variables:
purchaseSectionHeaderRow
BackgroundBrush,
purchaseSectionLeft,
purchaseSectionTop,
purchaseSectionWidth,
purchaseSectionRowHeight.
Additional information
a.
For more information about filled shapes, see the following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. For additional
information about drawing 2-D filled shapes, search by using the
phrases Drawing Lines and Shapes with GDI+ and GDI+
Graphics.
When you use filled shapes
on a print document,
consider how the document
will look when it is
photocopied or printed by
using a gray scale.
8.
Use Task List to locate the
code section 'TODO: Draw
the horizontal lines inside
the Purchase Items table'.
Create the code statements
required to draw the interior
lines by using the following
variables:
sectionInteriorPen,
purchaseSectionLeft,
verticalPosition,
purchaseSectionRight,
verticalPosition.
In addition to using the
width and color properties to
change the appearance of a
line, you should consider
using line styles and line
caps.
a.
For more information about drawing lines, see the following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Using a Pen to Draw Lines and Rectangles, Drawing a Line
with Line Caps, and Using a Pen to Draw Lines and Shapes.
Module 6: Printing and Reporting in Windows Forms Applications
Tasks
9.
Use the Task List to locate
the code section 'TODO:
Draw the footer text'. Create
the code statements required
to draw the contents of the
printText variable by using
the variables footerFont,
footerBrush,
horizontalPosition, and
verticalPosition, where
horizontalPosition has a
value equal to the left
margin value of the page
and verticalPosition has a
value equal to the bottom
margin value of the page
minus the height of the font.
73
Additional information
a.
For more information about drawing and measuring text, see the
following resources:
•
Lesson: Constructing Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
Practice: How to Construct Print Document Content Using GDI+ in
Module 6, “Printing and Reporting in Windows Forms
Applications,” in Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
•
The Visual Studio .NET Help documentation. Search by using the
phrases Drawing Text with GDI+ and Fonts and Text.
By default, text is drawn
below and to the right of the
position specified in a
DrawString command.
10. Rebuild the Lab06Class
project, reconstruct the
reference to the class library
in the Lab06Application
project, and then view the
updated print document by
using Lab06Application.
11. Save your projects, and then
close Visual Studio .NET.
a.
For more information about building and debugging your application,
use the following resource:
•
The Visual Studio .NET Help documentation. Search by using the
phrases Default and Custom Builds and Using the Debugger.
Additional information is not necessary for this task.
74
Module 6: Printing and Reporting in Windows Forms Applications
The following tables provide information required to construct the NT-2555P
and NT-2555L forms, which are the official Northwind Traders purchase order
documents.
Page Layout Table for Forms NT-2555P and NT-2555L
Document region/feature
Size constraint,
NT-2555P (portrait)
Size constraint,
NT-2555L (landscape)
Top Margin
1.0 inch (25.4 mm)
0.85 inch (21.6 mm)
Left Margin
1.2 inch (30.5 mm)
1.6 inch (40.6 mm)
Right Margin
0.8 inch (20.3 mm)
1.0 inch (25.4 mm)
Bottom Margin
1.0 inch (25.4 mm)
0.7 inch (17.8 mm)
Document Title Area
10% of available
height*, full width
Same as NT-2555P
Address Table
25% of available
height*, full width
Same as NT-2555P
Purchase Table
62.5% of available
height*, full width
Same as NT-2555P
This table is incomplete. The complete Page Layout Table for Forms NT-2555P
and NT-2555L table would contain additional information required to recreate the
NT-2555P and NT-2555L forms. Information has been left out of this table because
the additional information is not required to complete the exercises in this lab.
* The available height is the distance between the top and bottom margins.
Vector Objects Table for Forms NT-2555P and NT-2555L
Document region/feature
Object type
Pen/brush details
Page Border
Rectangle
Dashed line type, 3 point
(pt) width, gray
Address Table, border lines
Rectangle
Solid line type, 2 pt
width, blue
Address Table, interior lines
Line
Solid line type, 1 pt
width, blue
Address Table, 'Ship To' rows
Filled Rectangle
Light-gray brush fill
Purchase Table, border lines
Rectangle
Solid line type, 2 pt
width, blue
Purchase Table, interior lines
Line
Solid line type, 1 pt
width, blue
Order Item Table, header row
Filled Rectangle
Light-blue brush fill
Module 6: Printing and Reporting in Windows Forms Applications
75
Font Specification Table for Forms NT-2555P and NT-2555L
Font details
(font name, style, point
size, and color)
Text layout
(position in region)
Company Name
Microsoft Sans Serif,
Bold, 16 pt, Blue
Center-left position in
Document Title region
Company Address
Microsoft Sans Serif,
Regular, 8 pt, Blue
Immediately to the right
of, and bottom-aligned
to Company Name
Address Table Labels
Microsoft Sans Serif,
Regular, 7 pt, Gray
Offset 10% of the font
height from the top-left
corner of the cell
Address Table Text
Microsoft Sans Serif,
Regular, 10 pt, Black
Offset 25% of the font
height from the left side
of the cell and down
110% of the font height
from the top of the cell
Order Item Table Header
Microsoft Sans Serif,
Regular, 10 pt, Black
Centered in the cell
Order Item Table Text:
Quantity, Unit Price, Discount
Microsoft Sans Serif,
Regular, 9 pt, Black
Right justified in the cell
with an offset of 25% of
the font height
Order Item Table Text: Product
Description, Unit Size
Microsoft Sans Serif,
Regular, 9 pt, Black
Left justified in the cell
with an offset of 25% of
the font height
Document region/feature
THIS PAGE INTENTIONALLY LEFT BLANK
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertising