I’m trying to take a screenshot and display in a picturebox from a backgroundworker.
My problem is that i get this exception: Exception has been thrown by the target of an invocation.
Innerexception: Parameter is not valid.
Can someone explain why?
I’m using the using() blocks to prevent a memory leak.
public void DoStuff() {
var bw = new BackgroundWorker();
Bitmap b = null;
bw.DoWork += delegate {
Rectangle bounds = Screen.PrimaryScreen.Bounds;
using(Bitmap bmp = new Bitmap(bounds.Width,
bounds.Height,
PixelFormat.Format32bppArgb)) {
using(Graphics gfx = Graphics.FromImage(bmp)) {
x.CopyFromScreen(bounds.X,
bounds.Y,
0,
0,
bounds.Size,
CopyPixelOperation.SourceCopy);
b = bmp;
}
}
};
bw.RunWorkerCompleted += delegate {
pictureBox1.Image = b;
};
bw.RunWorkerAsync();
}
If you want to assign the bitmap to a PictureBox you should not be disposing of it. Dispose only the Graphics object that was used to create it. The garbage collector will dispose the Bitmap instance when the Form containing this PictureBox is disposed.
Also I would recommend you to pass the image to RunWorkerCompleted as parameter instead of capturing it in a closure: