Click here to Skip to main content
6,595,444 members and growing! (19,825 online)
Email Password   helpLost your password?
Languages » VB.NET » Windows Forms     Intermediate

VB.NET Form Library: Print Window

By George B Gilbert

A form library containing a print window that accepts any one of several controls as the print source
VB, Windows, .NET 2.0, Visual Studio, Dev
Posted:15 Nov 2007
Views:30,768
Bookmarked:34 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this article.
Popularity: 2.67 Rating: 4.43 out of 5

1

2

3
2 votes, 50.0%
4
2 votes, 50.0%
5
Screenshot - prwin_demo_main.gif

Screenshot - prwin_demo_print_window.gif

Contents

Introduction

This form library contains a print source class and a Windows form that are used to print the contents of a richtextbox, textbox, listbox, extended listbox or treeview control. Optionally, the text in the print window can be saved in either a richtext (.rtf) or text (.txt) file.

(Click here to read an article in which you will find information on how to build a form library.)

The Demo Project

The demo project is designed to illustrate all of the features and capabilities of the print window class library. There is one tab for each of the different controls that can be passed to the print window as print sources. When the demo application is started, populating the tabs may take several minutes because the "Treeview" tab is being populated with the directory structure from one of your hard drives (to 3 levels). The Richtextbox and Textbox tabs are loaded from demo files. The Extended Listbox and Listbox tabs are populated with a series of dates.

The fonts in each of the data tabs may look strange. These fonts are different so you can see that the fonts survive through the print window to both the print preview and the printer. To view a tab in the print window, click on the tab and then the Print Window button.

You can change the Title in the print window by changing the contents of the "Print window title" textbox at the top of the project demo window. Other printing process properties are set on the Window Properties and Dialog Defaults tabs. All of the properties in the demo project are initially set to the default values in the print window class library.

C_Print_Source Class

The C_Print_Source class converts the contents of the control being printed into a standard interface that is consumed by the print window form.

Constructors

Constructor option Signature Description
No parameters Empty The print window richtextbox is empty with a default font of "Courier New"
RichTextBox RichTextBox Encapsulate the richtextbox richtext. Use the richtextbox font.
TextBox TextBox Encapsulate the textbox text. Use the textbox font.
ListBox ListBox Encapsulate the listbox text. Use the listbox font.
Extended ListBox Extended ListBox, Font Encapsulate the extended listbox text. Use the passed font which is normally the associated listbox font.
Treeview Treeview Encapsulate the treeview text. Use the treeview font.

Properties

The C_Print_Source class exposes eight properties. They are listed here in alphabetical order:

Property Variable type Set value (=) or (Parameters) Description
CenterHeaderText Boolean N/A Get/set the flag controlling whether the header text on the printed page is centered. Defaults to True.
ControlFont Font N/A Exposes the print source font.
DoubleSpaceRootNodes Boolean N/A Get/set whether a blank line is to be inserted before each treeview root node. Defaults to False.
HeaderText String = String Set text to be displayed/printed at the top of the printed page.
Richtext_Box RichTextBox N/A Exposes the richtextbox (does not include any text from the HeaderText property).
SourceType Integer N/A Exposes the print source type.
  • 0 = None
  • 1 = Extended Listbox
  • 2 = Treeview
  • 3 = Richtextbox
  • 4 = Textbox
  • 5 = Listbox
TreeviewIndent Integer = Integer Get/set the number of characters each child node is indented in the printing of a treeview. Values limited to range of 1 to 12. Defaults to 4.
Text RichTextBox N/A Exposes the richtext including any header text.

Print_Window Form

Methods

The Print_Window form class exposes one method.

Method Parameters Description
Go C_Print_Source Displays the print window.

Properties

The Print_Window form class exposes eighteen properties in four sections. The properties within each section are listed here in alphabetical order:

General

Property Variable type Set value (=) or (Parameters) Description
DocumentName String = String Get/set the name of the document to display (e.g. in the print queue). Defaults to "Print Window Document."
HideSelection Boolean N/A Get/set whether text selection is hidden when the richtextbox does not have the focus. Defaults to False.
ShowSave Boolean N/A Get/set whether the Save button is visible. Defaults to True.
TitleText String = String Get/set the text in the print window title bar. Defaults to "Print Window."

Page Setup Dialog

Property Variable type Set value (=) or (Parameters) Description
AllowMargins Boolean N/A Get/set whether margins can be set in the page setup dialog box. Defaults to True.
AllowOrientation Boolean N/A Get/set whether the page orientation option will be enabled in the page setup dialog box. Defaults to True.
AllowPaper Boolean N/A Get/set whether the paper source can be selected in the page setup dialog box. Defaults to True.
AllowPrinter Boolean N/A Get/set whether a printer can be selected in the page setup dialog box. Defaults to True.
BottomMargin Single = Single Get/set the bottom margin inches in the page setup dialog. Valid values are in the range -22 to 22. A value outside this range defaults to the end range value. Defaults to 1.
Landscape Boolean N/A Get/set whether the default orientation setting in the page setup dialog is landscape. Defaults to False.
LeftMargin Single = Single Get/set the left margin inches in the page setup dialog. Valid values are in the range 0 to 22. A value outside this range defaults to the end range value. Defaults to 1.
RightMargin Single = Single Get/set the right margin inches in the page setup dialog. Valid values are in the range 0 to 22. A value outside this range defaults to the end range value. Defaults to 1.
TopMargin Single = Single Get/set the top margin inches in the page setup dialog. Valid values are in the range -22 to 22. A value outside this range defaults to the end range value. Defaults to 1.

Print Dialog

Property Variable type Set value (=) or (Parameters) Description
AllowPrintToFile Boolean N/A Get/set whether the print to file checkbox is enabled in the print dialog box. Defaults to True.
AllowSelection Boolean N/A Get/set whether the selection radio button is enabled in the print dialog box. Defaults to True.
AllowSomePages Boolean N/A Get/set whether the From...To...Page radio button is enabled in the print dialog box. Defaults to True.

Page Setup And Print Dialog

Property Variable type Set value (=) or (Parameters) Description
ShowHelp Boolean N/A Get/set whether the help button is enabled in the page setup and print dialog boxes. Defaults to False.
ShowNetwork Boolean N/A Get/set whether the network button is enabled in the page setup and print dialog boxes. Defaults to False.

Using the Code

Project Reference

To make the print window form library available in a project, follow these steps:

  1. Copy these class libraries to the project's bin (or bin\Debug, or bin\Release) folder
    • ExtendedRichTextBox.dll
    • tgs_extended_listbox.dll
    • tgs_print_window.dll
    • tgs_toolkit.dll
  2. Add this class library to the project's References
    • tgs_print_window.dll
  3. Add this Imports statement to each class that consumes the print window class
Imports tgs_print_window

Consuming The Class Library

The Print Button click event in the demo project illustrates how easily the print window class can be consumed in your project. First, the print source object is instantiated and configured. Then the print window is also instantiated and all necessary properties are set. Lastly, the print window is invoked. That's it!

    Private Sub btnPrintWindow_Click(ByVal sender As System.Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles btnPrintWindow.Click
        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  10/18/2007 G Gilbert            Original code

        '---------------------------------------------------


        '---------------------------------------------------

        ' Instantiate the print source object and set

        ' properties

        '---------------------------------------------------

        TurnOnHourglass()
        Dim ps As C_Print_Source = Nothing
        Select Case tabSamplesControl.SelectedIndex
            Case 0          ' Richtextbox

                ps = New C_Print_Source(rtbText)
            Case 1          ' Textbox

                ps = New C_Print_Source(txtBox)
            Case 2          ' Extended listbox

                ps = New C_Print_Source(el, lstExtendedListbox.Font)
            Case 3          ' Listbox

                ps = New C_Print_Source(lstListbox)
            Case 4          ' Treeview

                ps = New C_Print_Source(tvwTreeview)
                With ps
                    .DoubleSpaceRootNodes = chkDoubleSpace.Checked
                    .TreeviewIndent = cboIndent.SelectedIndex + 1
                End With
        End Select
        With ps
            .HeaderText = txtHeaderText.Text
            .CenterHeaderText = chkCenter.Checked
        End With

        '---------------------------------------------------

        ' Instantiate the print window object and set

        ' properties

        '---------------------------------------------------

        Dim pw As New tgs_print_window.Print_Window
        With pw
            .TitleText = txtPrintWindowTitle.Text
            .DocumentName = txtDocumentName.Text
            .HideSelection = chkHideSelection.Checked
            .ShowSave = chkShowSaveButton.Checked
            .AllowMargins = chkAllowMargins.Checked
            .AllowOrientation = chkAllowOrientation.Checked
            .AllowPaper = chkAllowPaper.Checked
            .AllowPrinter = chkAllowPrinter.Checked
            .Landscape = chkLandscape.Checked
            .TopMargin = CType(nudTopMargin.Value, Single)
            .BottomMargin = CType(nudBottomMargin.Value, Single)
            .LeftMargin = CType(nudLeftMargin.Value, Single)
            .RightMargin = CType(nudRightMargin.Value, Single)
            .AllowPrintToFile = chkAllowPrintToFile.Checked
            .AllowSelection = chkAllowSelection.Checked
            .AllowSomePages = chkAllowSomePages.Checked
            .ShowHelp = chkShowHelp.Checked
            .ShowNetwork = chkShowNetwork.Checked
        End With

        '---------------------------------------------------

        ' Display the print window

        '---------------------------------------------------

        pw.Go(ps)

        '---------------------------------------------------

        ' Clean up

        '---------------------------------------------------

        ps = Nothing
        pw = Nothing
        txtPrintWindowTitle.Focus()

    End Sub

Points Of Interest

ExtendedRichTextBox

The richtextbox used in the print window form is the ExtendedRichTextBox. You can read more about this versatile control in an article by salysle titled Building a Simple Word Processor Around an Extended RichTextBox Control.

The ExtendedRichTextBox, as you can see in the following code, offers a very simple way to print richtext. (Based on comments I read on various forums, this control may not be appropriate for general use as a richtextbox, however, it works very well as a print engine.)

#Region " ... Preview "
    Private Sub Preview_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Preview.Click
        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  07/17/2006 G Gilbert            Original code

        '---------------------------------------------------


        _printDocument.DocumentName = _documentName
        With _printPreviewDialog
            .WindowState = FormWindowState.Maximized
            .ShowDialog()
        End With
        rtbText.Focus()

    End Sub
#End Region
#Region " ... Print "
    Private Sub btnPrint_Click(ByVal sender As System.Object, _
                               ByVal e As System.EventArgs) _
                               Handles btnPrint.Click
        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  07/17/2006 G Gilbert            Original code

        '---------------------------------------------------


        If _printDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            _printDocument.Print()
        End If
        rtbText.Focus()

    End Sub
#End Region
#Region " Printing Events "
#Region " ... _printDocument_BeginPrint "
    Private Sub _printDocument_BeginPrint(ByVal sender As Object, _
                                    ByVal e As 
                                    System.Drawing.Printing.PrintEventArgs) _
                                    Handles _printDocument.BeginPrint
        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  10/18/2007 G Gilbert            Original code

        '---------------------------------------------------


        '---------------------------------------------------

        ' Initialize the number of characters already printed

        '---------------------------------------------------

        _checkPrint = 0

    End Sub
#End Region
#Region " ... _printDocument_PrintPage "
    Private Sub _printDocument_PrintPage(ByVal sender As System.Object, _
                     ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
                     Handles _printDocument.PrintPage
        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  10/18/2007 G Gilbert            Original code

        '---------------------------------------------------


        _checkPrint = rtbText.Print(_checkPrint, rtbText.TextLength, e)
        If _checkPrint < rtbText.TextLength Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

    End Sub
#End Region
#End Region

Appending Richtext

Appending the text from one richtextbox to another richtextbox, such that the richtext code is preserved, proved interesting. I found several approaches on the Internet, however, the below code that I wrote proved to be the simplest. This function is available in the tgs_toolkit.dll class library.

    Public Function AppendRTF(ByVal ParentRTB As RichTextBox, _
                              ByVal AppendRTB As RichTextBox) As RichTextBox
        '---------------------------------------------------

        ' Append the text (including richtext) from one

        ' richtextbox (AppendRTB) to the text in another

        ' richtextbox (ParentRTB)

        '---------------------------------------------------

        '     Date          Developer      Code Change

        '  ---------- -------------------- -----------------

        '  10/28/2007 G Gilbert            Original code

        '---------------------------------------------------


        '---------------------------------------------------

        ' Place the insertion cursor at the end of the

        ' parent richtextbox

        '---------------------------------------------------

        ParentRTB.SelectionStart = ParentRTB.Text.Length
        ParentRTB.SelectionLength = 0

        '---------------------------------------------------

        ' Select all of the text being appended

        '---------------------------------------------------

        appendRTB.SelectAll()

        '---------------------------------------------------

        ' Append the text (with richtext) and return

        '---------------------------------------------------

        ParentRTB.SelectedRtf = appendRTB.SelectedRtf
        appendRTB.DeselectAll()
        Return ParentRTB

    End Function

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

George B Gilbert


Member
Click here to see a complete list of my articles.
Occupation: Software Developer
Company: 2 Good Software
Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
NewsQuick Print Pinmemberpablleaf7:20 23 Apr '08  
GeneralRe: Quick Print PinmemberGeorge B Gilbert15:47 23 Apr '08  
GeneralThis is great! Pinmemberpablleaf6:52 23 Apr '08  
GeneralRe: This is great! PinmemberGeorge B Gilbert15:46 23 Apr '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Nov 2007
Editor: Sean Ewington
Copyright 2007 by George B Gilbert
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project