问题描述
我想做一个全屏抓屏并将其加载到一个图片框,但它给我这个错误:
的类型的第一个机会异常'System.ArgumentException'发生在System.Drawing.dll程序
其他信息:Ongeldige参数的
I'm trying to make a fullscreen screencapture and load it into an pictureBox, but it's giving me this error:A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dllAdditional information: Ongeldige parameter.
code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
{
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
pictureBox1.Image = bmpScreenCapture;
}
Joery。
推荐答案
时出现异常,因为使用
语句它分配给 pictureBox1.Image ,所以该图片无法显示位图时,它的时间重绘自己:
The exception occurs because the using
statement disposes of the Bitmap after it's assigned to pictureBox1.Image
, so the PictureBox is unable to display the bitmap when it's time to repaint itself:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
{
// ...
pictureBox1.Image = bmpScreenCapture;
} // <== bmpScreenCapture.Dispose() gets called here.
// Now pictureBox1.Image references an invalid Bitmap.
要解决这个问题,保持位图变量声明和初始化,但删除使用
:
To fix the problem, keep the Bitmap variable declaration and initializer, but remove the using
:
Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
// ...
pictureBox1.Image = bmpScreenCapture;
您仍应确保位图得到最终处置,但只有当你真的不需要它了(例如,如果替换 pictureBox1.Image
由另一位图后)。
You should still make sure the Bitmap gets disposed eventually, but only when you truly don't need it anymore (for example, if you replace pictureBox1.Image
by another bitmap later).
这篇关于类型的第一次机会异常'System.ArgumentException'发生在System.Drawing.dll程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!