0

While strolling around in the methods of the Graphics class, I bounced on the CopyFromScreen method. He, so why not make a screen capture utility!
I know there is lots of this stuff out there. But it just seems like fun to try to make one myself. I made a little Forms application with two forms: a controllerform and a transparant form on which I can draw a selection rectangle using MouseDown, MouseMove and MouseUp event handlers. I will not give the full code here but just the fully annotated method that does the actual copying and saving. Enjoy!

private void SaveCapture(string Fname)  
    //Fname is the name of the file where you want to save your screencapture
    //you can obtain a filename from a save file dialog
{
    //construct a rectangle from the topleft and bottomright points of your screenselection
    //if you want to capture the whole screen use Screen.GetBounds
    Rectangle ImageBounds = new Rectangle(_TopLeftPt.X, _TopLeftPt.Y,
                 _BottomRightPt.X - _TopLeftPt.X, _BottomRightPt.Y - _TopLeftPt.Y);
    
    //now make a bitmap the size of this rectangle
    Bitmap bmap = new Bitmap(ImageBounds.Width, ImageBounds.Height);

    //Create a Graphics object from this bitmap
    Graphics G = Graphics.FromImage(bmap);
    
    //this is the thing that does it!
    // It copies the colorbits from the screen to our graphics object, wich is a bitmap
    //_TopLeftPt is where our screenselection begins (the source)
    //Point.Empty is Point(0,0) which is the topleft of our bitmap (the destination)
    G.CopyFromScreen(_TopLeftPt, Point.Empty, ImageBounds.Size);

    //save our bitmap in bitmap format
    //this can be changed to jpeg and other formats if you want to
    bmap.Save(Fname, ImageFormat.Bmp);

    //no longer need for these things
    G.Dispose();
    bmap.Dispose();
}
2
Contributors
2
Replies
6
Views
8 Years
Discussion Span
Last Post by ddanbe
0

It is much better to use using blocks for your Bitmap and Graphics objects.

using (Bitmap bmap = new Bitmap(ImageBounds.Width, ImageBounds.Height))
    using (Graphics G = Graphics.FromImage(bmap))
    {    
        G.CopyFromScreen(_TopLeftPt, Point.Empty, ImageBounds.Size);

        bmap.Save(Fname, ImageFormat.Bmp);
    }

That way, if an exception occurs, the objects will be properly disposed of.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.