本程序中,定义了objPrintDocument为一个打印类。然后调用PrintDialog的AllowPrintToFile属性,是否启用打印到文件。然后用了If...Else...End If语句,如果TextBox5的内容不为空的话又执行一个If...Then...End If语句,如果用户点击了打印的确定按钮,则执行一个Try...Catch语句。Try语句里面定义PrintDoc为PrintDocument类,然后连接事件PrintDoc.PrintPage,并引用过程PrintText。接着调用PrintDocument的Print方法。Catch语句里面弹出对话框显示"sorry"。
此软件的打印部分程序如下:
Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
Dim objPrintDocument As PrintDocument = New PrintDocument()
objPrintDocument.DocumentName = "Text File Print "
PrintDialog1.AllowPrintToFile = False
PrintDialog1.AllowSelection = False
PrintDialog1.AllowSomePages = False
PrintDialog1.Document = objPrintDocument
If TextBox5.Text <> Nothing Then
If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Try
Dim PrintDoc As PrintDocument = New PrintDocument()
AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText
PrintDoc.Print()
Catch ex As Exception
MessageBox.Show("sorry", ex.ToString)
End Try
End If
Else
MsgBox("Please open a file frist! ", MsgBoxStyle.OkOnly)
End If
End Sub
通用过程PrintText里面用到了两个If...Then...End If语句。第一个If...Else...End If语句,如果TextBox5不为空,则调用Split函数拆分字符串并赋值给前面定义的字符串数组MyArr。若TextBox5为空,则弹出对话框提示请打开一个文件。在第二个If...Then...End If语句里面,如果字符串数组MyArr的长度大于0,则执行有限循环For...Next语句。在For...Next语句里面设置了打印界面的宽度尺寸。然后调用了Graphics的DrawString方法,在指定的位置用指定的文本格式绘制指定的文本字符串。接着设置了绘图对象的HasMorePages属性,设为False,只打印一页。
Private Sub PrintText(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim sngTopMargin As Single = ev.MarginBounds.Top
Dim widthOfprint As Integer 基于VB.NET的辐射报警仪上位机管理软件设计(15):http://www.youerw.com/tongxin/lunwen_2658.html