3

I have a form with controls, I need capture this form to image. Please help me. Thanks.

Leo Vo
  • 9,980
  • 9
  • 56
  • 78

2 Answers2

6
//Control cntrl; previously declared and populated
            Bitmap bmp = new Bitmap(cntrl.Width,cntrl.Height);
            cntrl.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
Djole
  • 1,145
  • 5
  • 10
  • Not much of an improvement to this, but you can also use cntrl.DisplayRectangle instead of creating a Rectangle yourself. – Jeff Apr 18 '18 at 13:48
0

This works (almost) for me. I did note that MANY times the image would just be blank. When I searched online, it seems that many people were having this issue with the webBrowser control. It turns out that the initial image sometimes needs to be cleared to a solid color for this control. I really don't know why, but once it is initialized, I get much more consistent results. I've yet to get a blank image back.

Please note the code I've attached for clearing the initial image to all black.

    try
    {
        string fn = Path.Combine(Path.GetTempPath(), "Error_screen.png");
        Bitmap bmp = new Bitmap(internalBrowser.Width, internalBrowser.Height);

        // In order to use DrawToBitmap, the image must have an INITIAL image. 
        // Not sure why. Perhaps it uses this initial image as a mask??? Dunno.
        using (Graphics G = Graphics.FromImage(bmp))
        {
            G.Clear(Color.Black);
        }

        internalBrowser.DrawToBitmap(bmp, new Rectangle(0, 0, 
                    internalBrowser.Width, internalBrowser.Height));

        bmp.Save(fn, ImageFormat.Png);
    }
    catch
    {
        // handle exceptions here.

        return "";
    }

One VERY interesting side note (as compared to other solutions I've seen): This works for my control which is on a form that I have never shown! My form exists as a headless web browser, but this actual form has never seen the light of day.

Jerry
  • 4,507
  • 9
  • 50
  • 79