A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll

让人想犯罪 __ 提交于 2020-01-15 07:35:09

问题


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.


回答1:


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




回答2:


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;



回答3:


You can try it, it will work

  pictureBox1.Image = new Bitmap(sourceBitmap);


来源:https://stackoverflow.com/questions/22273196/a-first-chance-exception-of-type-system-argumentexception-occurred-in-system-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!