I havea .NET (C#)application that regularly (approx. every 10 seconds) take a screenshot via System.Drawing.Graphics.CopyFromScreen(). This works fine almost all of the time, but once in a while I get this exception:
Code Snippet
System.ArgumentException: Parameter is not valid.
at System.Drawing.Graphics.GetHdc()
at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
at System.Drawing.Graphics.CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
After this error occurs once then further attempts to capture the screen also fail. I have discovered, however, that if I end the thread that is doing this and restart a new one then it can continue to capture the screen successfully.
The way that I'm creating the Graphics object from which I'm doing the capture is:
Code Snippet
using
(Bitmap bitmap = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppArgb))
{
using(Graphics graphics = Graphics.FromImage(bitmap))
{
...my code...
}
}
My question is, how can I avoid these problems in the first place?
Any suggestions would be greatly appreciated.