【Winform】打印画面

1.添加PrintDocument控件

2.绑定PrintDocument的PrintPage方法

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        e.Graphics.DrawImage(bmp, 
00)
    
End Sub

3.在QueryPageSettings方法中指定打印属性

    Private Sub PrintDocument1_QueryPageSettings(ByVal sender As ObjectByVal e As System.Drawing.Printing.QueryPageSettingsEventArgs) Handles PrintDocument1.QueryPageSettings
        e.PageSettings.Landscape 
= True
    
End Sub

4.调用gdi32.dll。gdi32.dll是Windows GDI图形用户界面相关程序,用于辅助创建组建。

    Public Declare Auto Function BitBlt Lib "gdi32.dll" (hObject As IntPtr, nXDest As Integer, nYDest As Integer, nWidth As Integer, nHeight As Integer, hObjSource As IntPtr, _
     nXSrc 
As Integer, nYSrc As Integer, dwRop As IntegerAs Long

5.将窗体截图打印

    Private bmp As Bitmap

    
Private Sub PrintMain()
        
Dim width As Integer, height As Integer
        
Dim gForm As Graphics = Graphics.FromHwnd(Me.Handle)
        width 
= CInt(gForm.VisibleClipBounds.Width)
        height 
= CInt(gForm.VisibleClipBounds.Height)
        bmp 
= New Bitmap(width, height)
        
Dim gBmp As Graphics = Graphics.FromImage(bmp)
        
Dim formHDC As IntPtr = gForm.GetHdc()
        
Dim bmpHDC As IntPtr = gBmp.GetHdc()
        API.BitBlt(bmpHDC, 
00, width, height, formHDC, _
         
00&HCC0020)
        gBmp.ReleaseHdc(bmpHDC)
        gForm.ReleaseHdc(formHDC)
        PrintDocument1.Print()
    
End Sub