1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| Public Class Form1
Private Const WM_PRINT As Integer = &H317
Private Const PRF_CLIENT As Integer = &H4
Private Const PRF_CHILDREN As Integer = &H10
Private WithEvents _PrintDocument As New System.Drawing.Printing.PrintDocument ' déclaration de l'objet qui sert à imprimer
Private _ImageForm As System.Drawing.Bitmap
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim hdc As IntPtr = IntPtr.Zero
Dim g As System.Drawing.Graphics = Nothing
Try
_ImageForm = New System.Drawing.Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height) ' on créé l'image à la bonne taille
g = System.Drawing.Graphics.FromImage(_ImageForm) ' on instancie g en disant que tout ce qui est fait sur ce graphics est fait aussi sur l'image
hdc = g.GetHdc ' récupération du handle windows de ce graphics
Dim wParam As IntPtr = hdc
Dim lParam As IntPtr = New IntPtr(PRF_CLIENT Or PRF_CHILDREN)
Dim msg As System.Windows.Forms.Message = System.Windows.Forms.Message.Create(Me.Handle, WM_PRINT, wParam, lParam)
MyBase.WndProc(msg)
' ici img contient l'image de la form snas la barre de titre
_PrintDocument.Print() ' demande l'impression, ca déclenche en fait l'évènement printpage, géré plus bas
Catch ex As Exception
MsgBox("Erreur pendant la génération de l'impression")
Finally
If g IsNot Nothing Then
If hdc <> IntPtr.Zero Then g.ReleaseHdc(hdc) ' dans tous les cas il faut relacher le handle
g.Dispose()
End If
End Try
End Sub
Private Sub Impression(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _PrintDocument.PrintPage
Try
If _ImageForm Is Nothing Then
MsgBox("Erreur pendant la génération de l'impression #2")
End If
Dim srcrect As New System.Drawing.Rectangle(0, 0, _ImageForm.Width, _ImageForm.Height)
Dim destrect As New System.Drawing.Rectangle ' reste à coder destrect pour qu'il zoome l'image
destrect.X = CInt(e.PageSettings.PrintableArea.X) ' en attendant je le mets à stretch sur la page
destrect.Y = CInt(e.PageSettings.PrintableArea.Y)
destrect.Width = CInt(e.PageSettings.PrintableArea.Width)
destrect.Height = CInt(e.PageSettings.PrintableArea.Height)
e.Graphics.DrawImage(_ImageForm, destrect, srcrect, GraphicsUnit.Document)
Catch ex As Exception
MsgBox("Erreur pendant l'impression")
End Try
End Sub
End Class |