I'm trying to make a fullscreen screencapture and load it into an pictureBox, but it's giving me this error: A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: Ongeldige parameter.
Code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
{
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
pictureBox1.Image = bmpScreenCapture;
}
Joery.
You can try it, it will work
The exception occurs because the
using
statement disposes of the Bitmap after it's assigned topictureBox1.Image
, so the PictureBox is unable to display the bitmap when it's time to repaint itself:To fix the problem, keep the Bitmap variable declaration and initializer, but remove the
using
:You should still make sure the Bitmap gets disposed eventually, but only when you truly don't need it anymore (for example, if you replace
pictureBox1.Image
by another bitmap later).You are disposing the wrong bitmap. You should dispose the old image, the one you replaced, not the one you just created. Failure to do this correctly, other than crashing your program when the image is painted, will eventually bomb your program with this exception when it runs out of memory. As you found out. Fix: