1

I have a windows application (C#/.NET) that needs to take screenshots repeatedly.

Currently, I use the following code to take these screenshots:

System.Drawing.Bitmap contextBuilderAfterSetupPageLoaded = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(contextBuilderAfterSetupPageLoaded);
do
{
    graphics.CopyFromScreen((int)contextBuilderRect.Left, (int)contextBuilderRect.Top, 0, 0, new System.Drawing.Size(width, height), System.Drawing.CopyPixelOperation.SourceCopy);
    contextBuilderAfterSetupPageLoaded.Save(pathForScreenshotsTextBox.Text + @"\progress\" + "00SetupPage.png", ImageFormat.Png);

    updateCondition(someCondition);

} while (someCondition);

where updateCondition(someCondition) is pseudocode. In my code, there are some more complex condition updates, but I believe none of this code should in any way be the cause of the issue I am experiencing.

width is an int that stores the width - in pixels - of the window of which I need to take a screenshot (in this case 1936px) and height is the corresponding height of the window (1056px in this case).

contextBuilderRect is a Rect, and represents the bounding rectangle of the same window.

When debugging in Visual Studio, the code runs fine 9 out 10 times, and produces the desired screenshot. But roughly 1 out of 10 times, it fails on the contextBuilderAfterSetupPageLoaded.Save() method call with the following unhandled exception:

System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

I have verified that the path (which is a local path) passed to said method call is valid, and it shouldn't be some kind of permissions issue, since it works 9 out of 10 times. I have also verified to the best of my knowledge that all other variables used in above code hold valid data at the time of the method call.

Why would I be getting this "generic error in GDI+" exception randomly about 1 in 10 times, while it works the rest of the times?

And how can I fix it - short of just putting it in a try-catch block and retrying until the method completes successfully?

ChrisC
  • 822
  • 2
  • 10
  • 25
  • 1
    Thanks for that @Ian Kemp. I searched stackoverflow for similiar questions but didn't come across that one. I will try the suggestions in that question, and if the error stops appearing I'll answer your question with a Yes – ChrisC Mar 27 '20 at 15:53

0 Answers0