Question

I have a function that gets a screenshot, saves it, and returns the file name to the image. I'm using the Bitmap.Save method and I think I'm cleaning up after myself. It, however, works only once--if the user calls the routine another time I get a external exception with a very helpful "A generic error occurred in GDI+" message.

It can save to the directory that one time (permissions don't seem to be the problem). And, if I change the file name (with, say, a simple counter) it works all the time--just leaves a mess in the temp directory in my opinion.

I've read some MSDN articles that lead me to believe I think I'm leaving a lock on the file, but 'no idea what I'm doing incorrectly.

Here's the code:

Function GetImage()

    Dim tempFile As String = Path.GetTempPath() & "Screen_Log.jpg"

    Me.WindowState = FormWindowState.Normal
    Me.Activate()
    Me.Refresh()

    Dim bmpScreenshot As Bitmap = New Bitmap(Width, Height, PixelFormat.Format32bppArgb)
    Dim gfxScreenshot As Graphics = Graphics.FromImage(bmpScreenshot)

    gfxScreenshot.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, Me.Size, CopyPixelOperation.SourceCopy)

    ' *** Works once, then crashes here.
    bmpScreenshot.Save(tempFile, ImageFormat.Jpeg)

    bmpScreenshot.Dispose()
    gfxScreenshot.Dispose()

    Return tempFile

End Function

Any suggestions?

-Gnerf

Was it helpful?

Solution

Bitmaps can be very sticky. Try this and see if it fixes the issue. Try without the GC part and see if the using block are enough - otherwise add the garbage collection calls.

Function GetImage() As String
 Dim tempFile As String = Path.GetTempPath() & "Screen_Log.jpg"
 Using bmpScreenshot As Bitmap = New Bitmap(Width, Height, PixelFormat.Format32bppArgb)
  Using gfxScreenshot As Graphics = Graphics.FromImage(bmpScreenshot)
   gfxScreenshot.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, Me.Size, CopyPixelOperation.SourceCopy)
   bmpScreenshot.Save(tempFile, ImageFormat.Jpeg)
  End Using
 End Using
 GC.Collect()
 GC.WaitForPendingFinalizers()
 GC.Collect()
 Return tempFile
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top