0

Is it possible to create an image from a current form? For example on onLoad create a picture of the current state of the form in the root folder? To store what the user sees as a picture.

DaveL
  • 77
  • 1
  • 4
  • 13

2 Answers2

4

Try this,

using (var bmp = new Bitmap(this.Width, this.Height)) 
{
            this.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
            bmp.Save(@"c:\temp\screenshot.png");
}

This will use the forms width and height (this.Width, this.Height if you are using the current form to write the screen to disk) and draw it to bitmap!

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx

Ahmed ilyas
  • 5,722
  • 8
  • 44
  • 72
  • Nice! It also works for the Application.OpenForms[0].DrawToBitmap(...) to get a screen shot of the running application's main window. – gridtrak Mar 10 '20 at 18:12
2

This will return a 'FormShot' without borders, scrollbars, header etc. To save it simply use the Bitmap.Save method.

public static Bitmap TakeWindowScreenshot(Form window)

 {
   var b = new Bitmap(window.Width, window.Height);
   this.DrawToBitmap(b, new Rectangle(0, 0, window.Width, window.Height));

   Point p = window.PointToScreen(Point.Empty);

   Bitmap target = new Bitmap( window.ClientSize.Width, window.ClientSize.Height);
   using (Graphics g = Graphics.FromImage(target))
   {
     g.DrawImage(b, 0, 0,
                 new Rectangle(p.X - window.Location.X, p.Y - window.Location.Y, 
                               target.Width, target.Height),  
                GraphicsUnit.Pixel);
   }
   b.Dispose();
   return target;
}
TaW
  • 53,122
  • 8
  • 69
  • 111