【问题标题】:A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dllSystem.Drawing.dll 中出现“System.ArgumentException”类型的第一次机会异常
【发布时间】:2014-03-08 18:18:30
【问题描述】:

我正在尝试进行全屏截屏并将其加载到图片框中,但它给了我这个错误: 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;
    }

乔瑞。

【问题讨论】:

  • 哪个调用给了你错误?
  • @JoachimIsaksson pictureBox1.Image = bmpScreenCapture;
  • 第一次机会异常不一定是坏事,看看this blog post。你的这段代码真的会抛出异常或崩溃吗?
  • 您可能需要重新考虑using,它会在将位图设置为 PictureBox 图像时处理位图。

标签: c# graphics bitmap screenshot


【解决方案1】:

出现异常是因为using 语句在将位图分配给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.

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

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

// ...

pictureBox1.Image = bmpScreenCapture;

您仍应确保位图最终得到处置,但前提是您确实不再需要它(例如,如果您稍后将 pictureBox1.Image 替换为另一个位图)。

【讨论】:

    【解决方案2】:

    您正在处理错误的位图。您应该处理 old 图像,即您替换的图像,而不是您刚刚创建的图像。未能正确执行此操作,除了在绘制图像时使程序崩溃之外,最终会在内存不足时用此异常轰炸您的程序。正如你所发现的。修复:

    var bmpScreenCapture = new Bitmap(...);
    using (var g = Graphics.FromImage(bmpScreenCapture)) {
        g.CopyFromScreen(...);
    }
    if (pictureBox1.Image != null) pictureBox1.Image.Dispose();      // <=== here!!
    pictureBox1.Image = bmpScreenCapture;
    

    【讨论】:

      【解决方案3】:

      你可以试试,它会起作用的

        pictureBox1.Image = new Bitmap(sourceBitmap);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多