C#处理函数给出错误
我试图每隔10毫秒采取屏幕截图并将它们设置为带有Timer的Picturebox.image
。几秒钟的程序运行完美,但几秒钟后程序崩溃。我试图在代码的最后使用Dispose()
函数来清除内存,但Dispose函数也给出错误。 (定时器的增加区间不工作)C#处理函数给出错误
using System; using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gameBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Bitmap screenshot;
Graphics GFX;
private void button1_Click(object sender, EventArgs e)
{
timer1.enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
takescreenshot();
}
private void takescreenshot()
{
screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
GFX = Graphics.FromImage(screenshot);
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);
pictureBox1.Image = screenshot;
screenshot.Dispose();
}
}
}
该错误是
“类型的未处理的异常 'System.ArgumentException' 发生在System.Drawing.dll程序
其他信息:参数无效。“
而且程序崩溃(也许这是崩溃,因为内存溢出异常的?) As you can see in here
回答:
见Graphics.FromImage():
你应该总是调用Dispose方法以释放FromImage方法创建的图形和 相关资源。
此外,没有必要将图形保存在类级别。
考虑到这一点,你需要的是:
public Bitmap screenshot; private void takescreenshot()
{
if (screenshot != null)
{
screenshot.Dispose();
}
screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
using (Graphics GFX = Graphics.FromImage(screenshot))
{
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);
}
pictureBox1.Image = screenshot;
}
回答:
我建议改变之前,使用太多RAM:
pictureBox1.Image = screenshot; screenshot.Dispose();
到:
var oldScreenshot = pictureBox1.Image; pictureBox1.Image = screenshot;
GFX.Dispose();
if (oldScreenshot != null)
oldScreenshot.Dispose;
,以确保只要您分配一个新的屏幕即可处理旧屏幕截图。
回答:
1)其实你的第一个问题“参数是无效的。”是因为你配置了截图对象。 如果您尝试仅运行一次您的takescreenshot()方法 - 您将会得到此错误。我认为这是因为你将对象“截图”设置为PictureBox1.Image而不是立即处理它。这合乎逻辑! PictureBox不能渲染处置对象。
2)尝试修改代码的按钮处理这样的:
private Object thisLock = new Object(); private void button1_Click(object sender, EventArgs e)
{
Thread thr = new Thread(() =>
{
while (true)
{pictureBox1.Invoke((Action)(() =>
{
screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
GFX = Graphics.FromImage(screenshot);
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0,
Screen.PrimaryScreen.Bounds.Size);
pictureBox1.Image = screenshot;
}));
}
Thread.Sleep(10);
});
thr.Start();
}
工作正常!最好的方式是在picturebox完成渲染时获得事件,但是我没有发现任何关于此的内容。
以上是 C#处理函数给出错误 的全部内容, 来源链接: utcz.com/qa/266377.html