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).