Weebie
Weebie

Reputation: 230

Capturing bitmaps causing Out Of Memory exception

The Problem

I am currently trying to create an application that would create a gif/video (not decided yet) of a users screen as they replicate an issue on their computer. This obviously means that I need to create a screenshot periodically via a timer.

The problem is that after 25 seconds (always 25 seconds), I get an error saying that the system is out of memory.

Exception thrown: 'System.OutOfMemoryException' in System.Drawing.dll

Additional information: Out of memory.

My Code

Below is the code that is in the Timer Tick event:

Private DebugVid As New List(Of IntPtr)

Private Sub tmrDebug_Tick(sender As Object, e As EventArgs) Handles tmrDebug.Tick

    Dim CurrentScreen As Screen = Screen.PrimaryScreen
    For Each SCR As Screen In Screen.AllScreens
        If SCR.Bounds.Contains(MousePosition) Then
            CurrentScreen = SCR
        End If
    Next

    Using ScreenGrab As New Bitmap(CurrentScreen.Bounds.Width, CurrentScreen.Bounds.Height)
        Using g As Graphics = Graphics.FromImage(ScreenGrab)
            g.CopyFromScreen(New Point(CurrentScreen.Bounds.X, CurrentScreen.Bounds.Y), New Point(0, 0), ScreenGrab.Size)
            g.DrawImage(My.Resources.MyCursor, New Point(MousePosition.X - CurrentScreen.Bounds.X, MousePosition.Y))
        End Using
        DebugVid.Add(ScreenGrab.GetHbitmap())
    End Using

    GC.Collect()
End Sub

The first section just defines which screen the cursor is on so I knows which screen to create the bitmap of.

The second section creates the bitmap, applies a screenshot to it, draws a cursor at the mouse position, and then finally stores the integer pointer in a list.

Once the user has clicked a button to stop the recording, it converts it into a gif (at the moment).

The part of the code that is throwing an exception is the following line:

DebugVid.Add(ScreenGrab.GetHbitmap())

Any help is appreciated.

Upvotes: 3

Views: 87

Answers (1)

Bradley Uffner
Bradley Uffner

Reputation: 16991

That's potentially a lot of unmanaged GDI handles and bitmap data to keep in memory. I wouldn't be surprised at all if, after 25 seconds, you depleated the available handles, or even just the available process memory. You may want to consider saving each frame out to disk as it is recorded. Then when recording is done, processes the individual images in to a gif.

According to MSDN the number of GDI handles available to a process can range from 256 to 65536 depending on the operating system and configuration. Each screenshot you are taking is using up at least one handle, and many more are being used by your application and the .net framework.

Upvotes: 4

Related Questions