Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
632 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...