Reputation: 1907
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!
Upvotes: 2
Views: 3153
Reputation: 54433
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!
Upvotes: 6