Miroslac Ilic Miroslac Ilic - 2 months ago 16
C# Question

C# Screen Detection

I have code for screen detection:

private Image CaptureScreen()
{
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
Bitmap target = new Bitmap(screenSize.Width, screenSize.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.CopyFromScreen(0, 0, 0, 0, new Size(screenSize.Width, screenSize.Height));
}
return target;
}


I calling it with Timer every 2 ms

private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Image = CaptureScreen();
}


After 15 seconds app crashed, because using to much memory. How I can prevent this?

Answer

You should dispose of your bitmaps. In the timer1_Tick method:

var oldImage = pictureBox1.Image as IDisposable;
pictureBox1.Image = CaptureScreen();
if (oldImage != null)
{
    oldImage.Dispose();
}

Some additional information: The .NET Bitmap class "Encapsulates a GDI+ bitmap". Calling Dispose allows the resources used by the image to be reallocated.

Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.