更新时间:2022-05-28 08:11:18
您保持一个新的位图设置在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;
}
}