为什么将表单图像保存到 VB.Net 中的文件时出现错误?

Why do I get an error when saving image of a form to file in VB.Net?

我需要将应用程序表单的图像保存为图片文件,如 jpeg、bmp 或 png 等。

Internet 上的许多资源都提供了用于捕获表单图像的此代码示例或类似代码示例:

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

并保存该代码捕获的表单图像:

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

捕获表单图像的代码似乎可以工作(不会导致错误)但是将图像保存到文件的代码行出现此错误:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in >System.Drawing.dll A generic error occurred in GDI+.

我试过代码的变体,但在所有情况下都是将图像保存到文件的语句

.Save("c:\My Folder\Screenshot.png", System.Drawing.Imaging.ImageFormat.Png)

总是报异常错误。我究竟做错了什么?有什么建议吗?

您正在从屏幕(在您的 Form 的范围内)截取一个矩形,而不是您的 Form 屏幕截图。 但是,您不必直接从 tmpImage(因为它尚未发布)保存,而是从该图像的源副本保存。 下面的代码显示了如何(其中一种方式):

Using final As Bitmap = New Bitmap(TakeScreenShot(Me))
    final.Save("C:\My Folder\Screenshot.png")
End Using

正如安德鲁指出的那样,这很可能是权限问题。我这样做是为了让你可以尝试不同的位置。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim tmpImg As Bitmap = TakeScreenShot(Me)
    Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    path = IO.Path.Combine(path, "Screen.png")
    tmpImg.Save(path, System.Drawing.Imaging.ImageFormat.Png)
End Sub