I currently have this useful code that I found elsewhere on StackOverflow:
form.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
I have a form with a few text boxes/drop downs and a large picture box. I then have smaller picture boxes placed on top of this large picture box.
When I view the screenshot taken, it shows the form but the smaller picture boxes that have been placed over the large picture box are not displayed for some reason?
I see this limitation in the docs for Control.DrawToBitmap():
Controls inside containers are rendered in reverse order.
That would mean that if two controls overlap each other, the one normally rendered "underneath" the other (it's drawn first and then overdrawn by the overlapping control) will instead be rendered last (so it will overlap the one that normally overlaps it). In your case, where a smaller control is drawn wholly inside the bounds of a larger one and on top of it, the control will be hidden by this reverse rendering.
Try working around this by using BringToFront() and SendToBack() on the larger PictureBox that is being overlapped by the smaller ones. Call BringToFront() just before drawing to the bitmap, then SendToBack() when you're done. If you don't want the user to see the screen flicker, try calling SuspendLayout() before making any Z-order changes, then ResumeLayout(true) after resetting to the proper Z-order.
Thank KeithS for helping me out!
For those who need the code to do these reverse & reverse back stuff, here you go:
private void ReverseControlZIndex(Control parentControl)
{
var list = new List<Control>();
foreach (Control i in parentControl.Controls)
{
list.Add(i);
}
var total = list.Count;
for (int i = 0; i < total / 2; i++)
{
var left = parentControl.Controls.GetChildIndex( list[i]);
var right = parentControl.Controls.GetChildIndex(list[total - 1 - i]);
parentControl.Controls.SetChildIndex(list[i], right);
parentControl.Controls.SetChildIndex(list[total - 1 - i], left);
}
}
private void SaveImage()
{
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png|Tiff Image (.tiff)|*.tiff|Wmf Image (.wmf)|*.wmf";
if (sf.ShowDialog() == DialogResult.OK)
{
int width = pnlCanvas.Size.Width;
int height = pnlCanvas.Size.Height;
Bitmap bm = new Bitmap(width, height);
SuspendLayout();
// reverse control z-index
ReverseControlZIndex(pnlCanvas);
pnlCanvas.DrawToBitmap(bm, new Rectangle(0, 0, width, height));
// reverse control z-index back
ReverseControlZIndex(pnlCanvas);
ResumeLayout(true);
bm.Save(sf.FileName, ImageFormat.Bmp);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With