我有一个组合框,里面有一些控件,我想把它发送到打印机。
我有这个代码可以从groupbox构建bmp文件。如何通过按钮点击将其发送到打印机?
Private Sub Doc_PrintPage(sender As Object, e As PrintPageEventArgs)
Dim x As Single = e.MarginBounds.Left
Dim y As Single = e.MarginBounds.Top
Dim bmp As New Bitmap(Me.GroupBox1.Width, Me.GroupBox1.Height)
Me.GroupBox1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.GroupBox1.Width, Me.GroupBox1.Height))
e.Graphics.DrawImage(DirectCast(bmp, Image), x, y)
End Sub
我有按钮点击事件:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim doc As New PrintDocument()
doc = Doc_PrintPage()
Dim dlgSettings As New PrintDialog()
dlgSettings.Document = doc
If dlgSettings.ShowDialog() = DialogResult.OK Then
doc.Print()
End If
End Sub
建议后的最终工作代码:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BMP = New Bitmap(GroupBox1.Width, GroupBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
GroupBox1.DrawToBitmap(BMP, New Rectangle(0, 0, GroupBox1.Width, GroupBox1.Height))
Dim pd As New PrintDocument
Dim pdialog As New PrintDialog
AddHandler pd.PrintPage, (Sub(s, args)
args.Graphics.DrawImage(BMP, 0, 0)
args.HasMorePages = False
End Sub)
pdialog.ShowDialog()
pd.PrinterSettings.PrinterName = pdialog.PrinterSettings.PrinterName
pd.Print()
End Sub
答案 0 :(得分:0)
这个想法是你有一个PrintDocument
对象,你调用它的Print
方法,它引发它的PrintPage
事件,你处理那个事件,在处理程序方法中你使用GDI +来绘制任何要打印的内容。所以,你需要摆脱这一行:
doc = Doc_PrintPage()
那可能做什么?您正尝试将方法的结果分配给PrintDocument
变量。为了使其有意义,该方法必须返回一个PrintDocument
对象,它没有。您需要做的是注册该方法来处理PrintPage
的{{1}}事件:
PrintDocument
如果你这样做,那么你也需要删除处理程序。更好的选择是将所有打印对象添加到设计器中的表单,然后为AddHandler doc.PrintPage, AddressOf Doc_PrintPage
创建PrintPage
事件处理程序,就像为PrintDocument
创建事件处理程序一样Button
。
有关打印的详细信息,您可能会发现this有用。