Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

c# - Take screenshot from window content (without border)

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

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

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...