A first chance exception of type 'System.Argum

2019-07-14 05:32发布

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.

3条回答
我命由我不由天
2楼-- · 2019-07-14 05:51

You can try it, it will work

  pictureBox1.Image = new Bitmap(sourceBitmap);
查看更多
何必那么认真
3楼-- · 2019-07-14 05:59

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

查看更多
Bombasti
4楼-- · 2019-07-14 06:03

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;
查看更多
登录 后发表回答