gpt4 book ai didi

C# 屏幕检测

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:05 24 4
gpt4 key购买 nike

我有屏幕检测代码:

private Image CaptureScreen()
{
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
Bitmap target = new Bitmap(screenSize.Width, screenSize.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.CopyFromScreen(0, 0, 0, 0, new Size(screenSize.Width, screenSize.Height));
}
return target;
}

我每 2 毫秒用 Timer 调用它

private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Image = CaptureScreen();
}

15 秒后应用程序崩溃,因为使用了太多内存。我该如何防止这种情况?

最佳答案

你应该处理掉你的位图。在 timer1_Tick 方法中:

var oldImage = pictureBox1.Image as IDisposable;
pictureBox1.Image = CaptureScreen();
if (oldImage != null)
{
oldImage.Dispose();
}

一些附加信息:.NET Bitmap类“封装 GDI+ 位图”。来电 Dispose允许重新分配图像使用的资源。

Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.

关于C# 屏幕检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com