|
|
Title | Print the contents of a ListBox left aligned, centered, or right aligned in Visual Basic 2005 |
Description | This example shows how to print the contents of a ListBox left aligned, centered, or right aligned in Visual Basic 2005. |
Keywords | print, ListBox, print preview, align, alignment, center, right align, left align, StringFormat, PrintDocument, PrintPage event |
Categories | Graphics, VB.NET |
|
|
When you click the Preview button, the program displays a print preview. The PrintDocument's PrintPage event handler uses the following code to display the list's items.
The code first builds a string containing all of the ListBox's items separated by carriage returns. It then creates a big font to print with.
Next the program makes a StringFormat object to determine how the text will be aligned. It sets the object's Alignment property to Near, Center, or Far to align the text on the left, middle, or right. (You could also set the object's LineAlignment property to Near, Center, or Far to align the printing vertically to the top, middle, or bottom.)
The code then uses the e.Graphics object's methods to draw the rectangle and draw the text inside it properly aligned.
|
|
' Build a string containing all of the items.
Dim txt As String = ""
For Each item As String In lstItems.Items
txt &= vbCrLf & item
Next item
txt = txt.Substring(vbCrLf.Length)
Using the_font As New Font("Times New Roman", 20, _
FontStyle.Regular, GraphicsUnit.Point)
' Left aligned.
Using sf As New StringFormat()
Dim rect As New Rectangle(1 * 100, 100, 150, 250)
sf.Alignment = StringAlignment.Near
e.Graphics.DrawRectangle(Pens.Red, rect)
e.Graphics.DrawString(txt, the_font, Brushes.Red, _
rect, sf)
End Using
' Centered.
Using sf As New StringFormat()
Dim rect As New Rectangle(3 * 100, 100, 150, 250)
sf.Alignment = StringAlignment.Center
e.Graphics.DrawRectangle(Pens.Green, rect)
e.Graphics.DrawString(txt, the_font, Brushes.Green, _
rect, sf)
End Using
' Right aligned.
Using sf As New StringFormat()
Dim rect As New Rectangle(5 * 100, 100, 150, 250)
sf.Alignment = StringAlignment.Far
e.Graphics.DrawRectangle(Pens.Blue, rect)
e.Graphics.DrawString(txt, the_font, Brushes.Blue, _
rect, sf)
End Using
End Using
e.HasMorePages = False
|
|
|
|
|
|