本文介绍了C#Graphics.CopyFromScreen"参数无效"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出了在C#中的应用程序,将继续执行屏幕捕获,并使用定时器在PictureBox显示。几秒钟后运行,有一个ArgumentException

I had made an app in C# that will perform screen capture continuously and display it in a PictureBox using timer. After running for a few seconds, there was an ArgumentException.

下面是code和具有ArgumentException的行

Below is the code and the line that has the 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内存不足的提示。

Besides that, I had notices that an alert saying low memory from Windows after running the app for a few seconds.

这是解决此问题的任何提示?

Any tips on resolving this problem?

推荐答案

您保持一个新的位图设置在PictureBox和previous位图是永远不会处理。一段时间后,系统运行短GDI处理和/或内存(运行你code,我消耗的存储器的一个演出下15秒)。

You keep setting a new bitmap to the picturebox, and the previous bitmap is never disposed. After a while, the system runs short of GDI handles and/or memory (running your code, I consumed one gig of memory in under 15 seconds).

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

You can simply reuse your existing bitmap:

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 在每次迭代。

You also don't have to reset pictureBox1.SizeMode on each iteration.

另外,您也可以手动处置previous位图:

Alternatively, you can dispose the previous bitmap manually:

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#Graphics.CopyFromScreen"参数无效"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:02