Search code examples
c#bitmapinvalidargumentexception

InvalidArgumentException when taking screenshot


Every second, I capture my screen with the following code. The first 40/50 times work, after that I get an InvalidArgumentException at the first and third line of code.

Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bmpScreenshot);
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
bmpScreen = bmpScreenshot;

Solution

  • Probably you need to dispose of some objects.

    It's hard to tell from just the code shown, but my guess would be that you're not properly disposing of objects and are running out of memory. I know for sure that Graphics objects should be disposed, and the bitmap likely needs to be disposed of as well when you're done with it. Depending on how your error catching is set up, if you swallow an out of memory exception and keep going then new objects that don't fit in the available memory will not be instantiated and their constructors will return null. If you then pass null to a method that doesn't want to receive null, an InvalidArgumentException is likely to result.