Search code examples
c#exceptionbitmapreturnscreenshot

System.ArgumentException on returned Bitmap


Relevant Code:

private Bitmap GetScreenShot()
    {
        Bitmap screenImage = null;

        using (screenImage = new Bitmap(panelPreview.Width, panelPreview.Height))
        {
            using (Graphics g = Graphics.FromImage(screenImage))
            {                    
                Rectangle rectanglePanelVideoPreview = panelPreview.Bounds;
                Point sourcePoints = panelPreview.PointToScreen(new Point(panelPreview.ClientRectangle.X, panelPreview.ClientRectangle.Y));
                g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
            }                
        }

        return screenImage;
    }

Bitmap screenImage throws an exception as I step through the code and get to

return screenImage

Screenshot

For some reason the integrity of the Bitmap fails after it leaves

using (screenImage = new Bitmap(panelPreview.Width, panelPreview.Height))
{...
}

Any assistance at all would be appreciated, thanks.


Solution

  • This happens because the code:

    using (screenImage = ...)
    {
    }
    

    Ends up disposing of screenImage. So what you end up returning is a disposed object.

    A slight modification of your code to remove the using will fix the problem:

    private Bitmap GetScreenShot()
    {
        Bitmap screenImage = new Bitmap(panelPreview.Width, panelPreview.Height))
        using (Graphics g = Graphics.FromImage(screenImage))
        {                    
            Rectangle rectanglePanelVideoPreview = panelPreview.Bounds;
            Point sourcePoints = panelPreview.PointToScreen(new Point(panelPreview.ClientRectangle.X, panelPreview.ClientRectangle.Y));
            g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
        }                
    
        return screenImage;
    }
    

    But you should remember to call Dispose on that bitmap when you're done using it. Especially if this is something that you'll be doing often.