Specifically: I need to capture as a bitmap a specific region of what a picturebox is actually displaying. The coordinates of the region are specified by the bounds of a con
This will copy and save the currently shown content of the PictureBox
including a BackgroundImage
(if there is one and if it shines through) and also all Controls
that belong to the PictureBox
, like Labels
etc.. Also included are elements drawn in the Paint
event. Things drawn outside the Paint
event are non-persistent and will not be included.
using (Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height))
{
pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
bmp.Save(yourfilename, ImageFormat.Png);
}
Note: On my test Form the PicureBox
is sitting inside an AutoScroll Panel pan_PBscroll
. The PictureBox is displaying pixels 1:1 and is therefore, with a photograph loaded, much bigger than the Panel, the Form or even the Screen. So to clip to the actually visible parts I could not use the pictureBox1.ClientSize
and pictureBox1.ClientRectangle
but used the dimensions of that Panel. This may well apply to you, too.
I'm not sure about your timing issues. But since you mentioned CopyFromScreen
here are a few differences:
CopyFromScreen
makes a 1:1 copy of each screen pixelControl.DrawToBitmap
makes the Control draw itself onto a Bitmap, just as it draws itself during Paint
Since you're using a PictureBox I would say to take a look PictureBox.Image where you can get the Bitmap object.
Hope it helps.