Have you ever wanted to print your Windows Form? Here's a waaaay cool way to print
the active Windows Form:
Friend Class PrintHelper
Private m_PrintBitmap As Bitmap
Private WithEvents m_PrintDocument As System.Drawing.Printing.PrintDocument
Private m_PrintDialog As PrintDialog
Private m_PrintDialogResult As DialogResult
Private Declare Auto Function BitBlt Lib "gdi32.dll"
(ByVal hdcDest As IntPtr, ByVal nXDest As Integer,
ByVal nYDest As Integer, ByVal nWidth As Integer,
ByVal nHeight As Integer, ByVal hdcSrc As IntPtr,
ByVal nXSrc As Integer, ByVal nYSrc As Integer,
ByVal dwRop As System.Int32) As Boolean
Private Const SRCCOPY As Integer = &HCC0020
Private mFormToPrint As System.Windows.Forms.Form
Friend Function Print(ByVal formToPrint As System.Windows.Forms.Form) As Boolean
Try
mFormToPrint = formToPrint
' Copy the form's image into a bitmap.
m_PrintBitmap = GetFormImage()
' Make a PrintDocument, bring up PrintDialog, and print
m_PrintDocument = New System.Drawing.Printing.PrintDocument
m_PrintDialog = New PrintDialog
m_PrintDialog.Document = m_PrintDocument
m_PrintDialogResult = m_PrintDialog.ShowDialog
If m_PrintDialogResult = DialogResult.OK Then
m_PrintDocument.Print()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
'**********************************************************************
' Returns the Form as a Bitmap
'**********************************************************************
Private Function GetFormImage() As Bitmap
' Get this form's Graphics object.
Dim me_gr As Graphics = mFormToPrint.CreateGraphics
' Make a Bitmap to hold the image.
Dim bm As New Bitmap(mFormToPrint.ClientSize.Width, mFormToPrint.ClientSize.Height, me_gr)
Dim bm_gr As Graphics = me_gr.FromImage(bm)
Dim bm_hdc As IntPtr = bm_gr.GetHdc
' Get the form's hDC. We must do this after
' creating the new Bitmap, which uses me_gr.
Dim me_hdc As IntPtr = me_gr.GetHdc
' BitBlt the form's image onto the Bitmap.
BitBlt(bm_hdc, 0, 0, mFormToPrint.ClientSize.Width, _
mFormToPrint.ClientSize.Height, me_hdc, 0, 0, SRCCOPY)
me_gr.ReleaseHdc(me_hdc)
bm_gr.ReleaseHdc(bm_hdc)
' Return the result.
Return bm
End Function
'**********************************************************************
' Draws the form on the page. Not currently used, but part of original code.
'**********************************************************************
Private Sub m_PrintDocument_PrintPage(ByVal sender As Object,
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles m_PrintDocument.PrintPage
' Draw the image centered.
Dim x As Integer = e.MarginBounds.X + _
(e.MarginBounds.Width - m_PrintBitmap.Width) \ 2
Dim y As Integer = e.MarginBounds.Y + _
(e.MarginBounds.Height - m_PrintBitmap.Height) \ 2
e.Graphics.DrawImage(m_PrintBitmap, x, y)
' There's only one page.
e.HasMorePages = False
End Sub
End Class
from a solution provided by Mike Cole in Message #1239236
|