Search code examples
c#capture

Capturing windows form into image


I know this question has been answered before. But none of the answers are correct. How can I capture the image of a windows form and save it. I use this:

Bitmap bmp = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
bmp.Save(@"C://Desktop//sample.png",ImageFormat.Png);

but get the error:

A generic error occurred in GDI+

I have also read about this error but none of the suggestions work for me! Please help


Solution

  • The problem is in bmp.Save(@"C://Desktop//sample.png",ImageFormat.Png);.

    First it must be @"C:\Desktop\sample.png", you don't need to escape anything with verbatim string.

    Second make sure the path is correct and you have permission to write to.

    Third as Sayse point out dispose the bitmap.

    using(Bitmap bmp = new Bitmap(this.Width, this.Height))
    {
        this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
        bmp.Save(@"C:\Desktop\sample.png",ImageFormat.Png); // make sure path exists!
    }