Re: Printing a Windows form
Here is an official MSDN documentation on how to print a form. https://learn.microsoft.com/en-us/do...t-windows-form
Here is a modified example to fit your use case:
Code:
Public Class frmDGVTest
Private WithEvents _printDocument As PrintDocument
Private _memoryImage As Bitmap
Private Sub frmDGVTest_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
If (e.KeyCode = Keys.F1) Then
Using myGraphics = Me.CreateGraphics()
Dim formSize = Me.Size
_memoryImage = New Bitmap(formSize.Width, formSize.Height, myGraphics)
Using memoryGraphics = Graphics.FromImage(memoryImage)
memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, formSize)
End Using
End Using
PrintDocument1.Print()
End If
End Sub
Private Sub PrintImage(sender As Object, e As PrintPageEventArgs) Handles _printDocument.PrintPage
e.Graphics.DrawImage(_memoryImage, 0, 0)
End Sub
End Class
Re: Printing a Windows form
WithEvents Is used to specify that a component included via code can have eventhandlers specified in code, so rather than using AddHandler…
Code:
Private Sub PrintImage(ByVal sender As Object, ByVal ppea As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Re: Printing a Windows form
Thank you dday9 and .paul. When I used the provided code, I got an error. The problem is this: I put a break point on the line 'PrintDocument1.Print()' and the debugger shows PrintDocument1 as being nothing (once I changed the name of the declared variable to match). The referenced code has the same issue - printDocument1 is never defined.
Okay - just solved the problem: the declaration should be
Code:
Private WithEvents _printDocument As New PrintDocumen
Re: Printing a Windows form
Yes, that was my problem. I free-typed the code and forgot to initialize the class. Thinking about it a bit more, unless you plan on changing the value of the variable, you should probably mark it as readonly too.
Code:
Private WithEvents _printDocument As PrintDocument = New PrintDocument()