System.Drawing.dll中发生了'System.ArgumentException'类型的第一次机会异常

Joe*_*ery 2 c# graphics screenshot bitmap

我正在尝试制作全屏截图并将其加载到pictureBox中,但它给了我这个错误: System.Drawing.dll中出现类型'System.ArgumentException'的第一次机会异常附加信息:Ongeldige参数.

码:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

Joery.

Mic*_*Liu 8

之所以发生异常,是因为using语句在分配后会处理Bitmap pictureBox1.Image,因此PictureBox在重绘自身时无法显示位图:

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.
Run Code Online (Sandbox Code Playgroud)

要解决此问题,请保留Bitmap变量声明和初始化程序,但删除using:

Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                     Screen.PrimaryScreen.Bounds.Height);

// ...

pictureBox1.Image = bmpScreenCapture;
Run Code Online (Sandbox Code Playgroud)

您仍应确保最终处理Bitmap,但仅限于您真正不再需要它时(例如,如果pictureBox1.Image稍后再替换为其他位图).