Hey everyone. In this tutorial, i will be showing you how to add a print button, to print out text from your form.
Let's get started. First, open up your visual basic studio and create a new windows form application. Once your form is up, add a button. Name it "Print".
Next, add a text box; multiline true.
Now let's code it. At the very top, above the Public Class heading, add this:
[HTML]
Imports System.Drawing.Printing
[/HTML]
Now that we told the program to import system drawing, (or printing) we can now give the form a function.
Now, UNDER the Public Class heading, enter this:
[HTML]
Private Sub PrintText(ByVal sender As Object, _
ByVal ev As PrintPageEventArgs)
ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", _
11, FontStyle.Regular), Brushes.Black, 120, 120)
ev.HasMorePages = False
[/HTML]
We just used DrawString to create text in a graphics object in the first line. Then we specified that it would be the last page to print in the second and third line.
Now, let's give the print button it's function.
Double-click the print button in the forms design. It will create your Private Sub for the button. In that sub, enter this:
[HTML]
Try
AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText
PrintDoc.Print()
Catch ex As Exception
MessageBox.Show("Sorry--there is a problem printing", ex.ToString())
End Try
[/HTML]
We just told the button to print to the local printer, also to catch any exceptions.
This is the end of this tutorial. Thank-you for reading and i hope it helped.