Search code examples
c#screenshot

Generic error in GDI+ occurs in Screen Capture


I am writing an application that takes screen shots, but randomly it will throw a GDI+ generic error. Unfortunately, a generic error does not help me debug well. My code for the screen capture is:

    static void CaptureScreen()
    {
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        // Create a graphics object from the bitmap
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        // Take the screenshot from the upper left corner to the right bottom corner
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        // Save the screenshot to the specified path that the user has chosen
        bmpScreenshot.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);
    }

Which will give me a generic error occasionally, so I thought "Maybe I should dispose the bitmap and graphics variable"

    static void CaptureScreen()
    {
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        // Create a graphics object from the bitmap
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        // Take the screenshot from the upper left corner to the right bottom corner
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        // Save the screenshot to the specified path that the user has chosen
        bmpScreenshot.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);

        bmpScreenshot.Dispose();
        gfxScreenshot.Dispose();
    }

and then delete said file:

            for (int i = 1; i == times; i++)
            {
                File.Delete(savePath + @"\img" + i.ToString() + ".png");
            }
            times = 0;

But if you run that twice it says the file is in use, if you are writing to the same file. Any ideas?


Solution

  • The following might help:

    using (bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb))
    using (gfxScreenshot = Graphics.FromImage(bmpScreenshot))
    {
        // Take the screenshot from the upper left corner to the right bottom corner
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
    
        Bitmap bmpScreenshot2 = new Bitmap(bmpScreenshot); // FIX: Change "S" to "s"...
        // Save the screenshot to the specified path that the user has chosen
        bmpScreenshot2.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);
    }