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.
The exception occurs because the using
statement disposes of the Bitmap after it's assigned to pictureBox1.Image
, so the PictureBox is unable to display the bitmap when it's time to repaint itself:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
{
// ...
pictureBox1.Image = bmpScreenCapture;
} // <== bmpScreenCapture.Dispose() gets called here.
// Now pictureBox1.Image references an invalid Bitmap.
To fix the problem, keep the Bitmap variable declaration and initializer, but remove the using
:
Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
// ...
pictureBox1.Image = bmpScreenCapture;
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:
var bmpScreenCapture = new Bitmap(...);
using (var g = Graphics.FromImage(bmpScreenCapture)) {
g.CopyFromScreen(...);
}
if (pictureBox1.Image != null) pictureBox1.Image.Dispose(); // <=== here!!
pictureBox1.Image = bmpScreenCapture;
You can try it, it will work
pictureBox1.Image = new Bitmap(sourceBitmap);