[英]How to release Bitmap, ReDraw Bitmap, and add it to PictureBox. Without leaking resources or causing much flicker
[英]PictureBox resources release
我想制作一个屏幕缩放器,以捕获屏幕的一部分并将其缩放。 现在,下面的代码可以捕获屏幕并在PictureBox中播放。 但是我有一个问题,就是在我打开程序时,我的记忆不断增长。 我认为一定有一些未发布的资源,我也不知道如何发布。
我将其像媒体播放器一样,但它不播放视频,而是播放当前屏幕的一部分。
public partial class Form1 : Form
{
PictureBox picBox;
Bitmap bit;
Graphics g;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
picBox = pictureBox;
}
private void CopyScreen()
{
bit = new Bitmap(this.Width, this.Height);
g = Graphics.FromImage(bit as Image);
Point upperLeftSource = new Point(
Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);
g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);
picBox.Image = Image.FromHbitmap(bit.GetHbitmap());
bit.Dispose();
g.Dispose();
}
private void timer_Tick(object sender, EventArgs e)
{
CopyScreen();
}
问题在于您对GetHbitmap
的使用,以及当您将新的Image
分配给PictureBox
时没有处置以前的Image
的事实。
https://msdn.microsoft.com/zh-CN/library/1dz311e4(v=vs.110).aspx指出:
您负责调用GDI DeleteObject方法以释放GDI位图对象使用的内存。
(您没有在做)
考虑更改代码以避免对GetHbitmap
调用(并Dispose
上一个Image
):
private void CopyScreen()
{
bit = new Bitmap(this.Width, this.Height);
g = Graphics.FromImage(bit);
Point upperLeftSource = new Point(
Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);
g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);
var oldImage = picBox.Image;
picBox.Image = bit;
oldImage?.Dispose();
g.Dispose();
}
为了进一步简化它,请删除您在类顶部声明的字段,然后使用:
private void CopyScreen()
{
var picBox = pictureBox;
var bit = new Bitmap(this.Width, this.Height);
using (var g = Graphics.FromImage(bit))
{
var upperLeftSource = new Point(
Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2,
Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2);
g.CopyFromScreen(upperLeftSource, new Point(0, 0), bit.Size);
var oldImage = picBox.Image;
picBox.Image = bit;
oldImage?.Dispose();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.