I need to save an image of my application's form to a picture file, like a jpeg, bmp, or png, etc.
Numerous sources on the internet give this or similar code examples for capturing an image of a form:
Private Function TakeScreenShot(ByVal Control As Control) As Bitmap
Dim tmpImg As New Bitmap(Control.Width, Control.Height)
Using g As Graphics = Graphics.FromImage(tmpImg)
g.CopyFromScreen(Control.PointToScreen(New Point(0, 0)), New Point(0, 0), New Size(Control.Width, Control.Height))
End Using
Return tmpImg
End Function
and this to save the image of the form captured by that code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TakeScreenShot(Me).Save("c:\My Folder\Screenshot.png", System.Drawing.Imaging.ImageFormat.Png)
End Sub
The code for capturing the form's image seems to work (does not result in an error) but the line of code saving the image to file gives this error:
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in >System.Drawing.dll A generic error occurred in GDI+.
I have tried variations of the code, but in all cases the statement for saving the image to file
.Save("c:\My Folder\Screenshot.png", System.Drawing.Imaging.ImageFormat.Png)
always gives the exception error. What am I doing wrong? Any suggestions?