2

I am searching a solution on how to save the content of a form in a bitmap with C#. I have already tried to use DrawToBitmap, but it captures all the window with the border.

That is the result of this code:

public static Bitmap TakeDialogScreenshot(Form window)
 {
    var b = new Bitmap(window.Bounds.X, window.Bounds.Y);
    window.DrawToBitmap(b, window.Bounds);
    return b;
 }   

Call is:

TakeDialogScreenshot(this);

Who thought it :D

I have already searched on google, but I did not manage to get it. Thanks!

Dominic B.
  • 1,897
  • 1
  • 16
  • 31

1 Answers1

6

Edit: While using the ClientArea is key, it isn't quite enough, as DrawToBitmap will always include the title, borders, scrollbars..

So after taking the full screen- or rather 'formshot', we'll have to crop it, using an offset we can get from mapping the origin of the clientarea to the screen coordinates and subtracting these from the form location, which already is in screen coordinates..:

public static Bitmap TakeDialogScreenshot(Form window)
{
   var b = new Bitmap(window.Width, window.Height);
   window.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;
}

Sorry for the error in my first post!

TaW
  • 53,122
  • 8
  • 69
  • 111
  • Hm, does not seem to help. :( – Dominic B. Apr 21 '14 at 11:09
  • I tried now, for the Bitmap I also set as parameters `window.ClientRectangle.Width` etc., but it always shows the complete form. So ClientRectangle did not go for it. – Dominic B. Apr 21 '14 at 11:17
  • Works very well! As I wished. Not a problem you had failed at first, you tried to help me and this is very kind. :) Thanks so much for this solution! – Dominic B. Apr 21 '14 at 12:51
  • 1
    It was hard to find this post as duplicate, Maybe editing the tags/title help future readers to find it easier? However I'll keep the [alternative solution](https://stackoverflow.com/a/54629851/3110834) which I posted as it's different solution. – Reza Aghaei Feb 12 '19 at 10:54
  • Sure, the more the merrier :-) - Not sure how to improve on the title though. It sounds like the right question.. Suggestions? – TaW Feb 12 '19 at 10:57