我用C#制作了一个应用程序,它将连续执行屏幕捕获,并使用计时器将其显示在PictureBox中。运行几秒钟后,出现ArgumentException。

下面是代码和具有ArgumentException的行

private void timer1_Tick(object sender, EventArgs e)
    {
        Rectangle bounds = Screen.GetBounds(Point.Empty);
        Graphics graphics;
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
        using (graphics = Graphics.FromImage(bitmap))
        {

            graphics.CopyFromScreen(0, 0, 0, 0, new Size(bounds.Width , bounds.Height )); // ArgumentException
            pictureBox1.Image = bitmap;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

        }
    }


除此之外,我还注意到,在运行该应用程序几秒钟后,有一则警报提示Windows内存不足。

解决此问题的任何技巧?

最佳答案

您一直在图片框中设置一个新的位图,并且以前的位图永远不会被丢弃。一段时间后,系统的GDI句柄和/或内存不足(运行您的代码,我在15秒内消耗了一个内存)。

您可以简单地重用现有的位图:

Rectangle bounds = Screen.GetBounds(Point.Empty);

Image bitmap = pictureBox1.Image ?? new Bitmap(bounds.Width, bounds.Height);

using (Graphics graphics = Graphics.FromImage(bitmap))
{
    graphics.CopyFromScreen(0, 0, 0, 0, new Size(bounds.Width, bounds.Height));

    if (pictureBox1.Image == null)
    {
        pictureBox1.Image = bitmap;
    }
    else
    {
        pictureBox1.Refresh();
    }

}


您也不必每次迭代都重置pictureBox1.SizeMode



或者,您可以手动处理以前的位图:

Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
    graphics.CopyFromScreen(0, 0, 0, 0, new Size(bounds.Width, bounds.Height));

    using (Image prev_bitmap = pictureBox1.Image)
    {
        pictureBox1.Image = bitmap;
    }
}

关于c# - C#Graphics.CopyFromScreen“参数无效”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16813919/

10-10 08:02