Click here to Skip to main content
6,596,602 members and growing! (18,741 online)
Email Password   helpLost your password?
Multimedia » General Graphics » Graphics     Intermediate

Screen Capturing

By Holzhauer

Capture screen contents without using any Win32 API calls, just using .NET (2.0) classes.
C#.NET 2.0, WinXP, GDI+, VS2005, Dev
Posted:31 Jan 2006
Updated:24 Mar 2006
Views:90,408
Bookmarked:168 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
39 votes for this article.
Popularity: 7.47 Rating: 4.70 out of 5
1 vote, 2.6%
1

2

3
6 votes, 15.8%
4
31 votes, 81.6%
5

Demo application

Introduction

There are a lot of articles about screen capturing, but most of them use Win32 API functions, even in .NET 2.0, where this is not necessary because .NET 2.0 has all classes needed to implement that.

Background

It's often necessary to get a screenshot of the entire screen or parts of it. In our applications, we often use systems with multiple monitors, requiring us to capture all of them at once or each screen separately. Just remember, the virtual screen is the complete view of all monitors attached to the system, the primary screen is the view of the main monitor, and the working screen is the same but excluding the task bar.

Using the code

The class 'ScreenCapture' supplies a couple of methods allowing to capture the complete virtual screen, the primary screen, the working screen, a specific form (complete or only the client area), and only the contents of a specific control in a form. The images captured may be used directly from your code, or they can be saved into a file or printed. There is another small helper class 'ImageFormatHandler' which is used to handle the different graphic file formats when saving the captured image.

The source

The source code files include the two classes described, and may be directly used in your code. It's built with Visual Studio 2005.

Our main capturing method looks like below:

public Bitmap[] Capture( CaptureType typeOfCapture )
{
    // used to capture then screen in memory
    Bitmap memoryImage;
    // number of screens to capture,
    // will be updated below if necessary
    int count = 1;

    try
    {
        Screen[] screens = Screen.AllScreens;
        Rectangle rc;

        // setup the area to capture
        // depending on the supplied parameter
        switch ( typeOfCapture )
        {
            case CaptureType.PrimaryScreen:
                rc = Screen.PrimaryScreen.Bounds;
                break;
            case CaptureType.VirtualScreen:
                rc = SystemInformation.VirtualScreen;
                break;
            case CaptureType.WorkingArea:
                rc = Screen.PrimaryScreen.WorkingArea;
                break;
            case CaptureType.AllScreens:
                count = screens.Length;
                typeOfCapture = CaptureType.WorkingArea;
                rc = screens[0].WorkingArea;
                break;
            default:
                rc = SystemInformation.VirtualScreen;
                break;
        }
        // allocate a member for saving the captured image(s)
        images = new Bitmap[count];

        // cycle across all desired screens
        for ( int index = 0; index < count; index++ )
        {
            if ( index > 0 )
                rc = screens[index].WorkingArea;
                // redefine the size on multiple screens

            memoryImage = new Bitmap( rc.Width, rc.Height, 
                          PixelFormat.Format32bppArgb );
            using ( Graphics memoryGrahics = 
                    Graphics.FromImage( memoryImage ) )
            {
                // copy the screen data
                // to the memory allocated above
                memoryGrahics.CopyFromScreen( rc.X, rc.Y, 
                   0, 0, rc.Size, CopyPixelOperation.SourceCopy );
            }
            images[index] = memoryImage;
            // save it in the class member for later use
        }
    }
    catch ( Exception ex )
    {
        // handle any erros which occured during capture
        MessageBox.Show( ex.ToString(), "Capture failed", 
            MessageBoxButtons.OK, MessageBoxIcon.Error );
    }
    return images;
}

The variable images used is a member of this class, and is of type Bitmap[]. The parameter typeOfCapture of this method is an enum type defined in this class, and is used to select what actually should be captured.

There is another capture method which is used to selectively capture the contents of controls, forms, or their client area. It works quite similar to the one shown above.

private Bitmap capture( Control window, Rectangle rc )
{
    Bitmap memoryImage = null;
    images = new Bitmap[1];

    // Create new graphics object using handle to window.
    using ( Graphics graphics = window.CreateGraphics() )
    {
        memoryImage = new Bitmap( rc.Width, 
                      rc.Height, graphics );

        using ( Graphics memoryGrahics = 
                Graphics.FromImage( memoryImage ) )
        {
            memoryGrahics.CopyFromScreen( rc.X, rc.Y, 
               0, 0, rc.Size, CopyPixelOperation.SourceCopy );
        }
    }
    images[0] = memoryImage;
    return memoryImage;
}

Several other methods are used to do all the work needed for saving/printing the captured image, they are all described in comments in the source code.

public void Save( String filename, 
       ImageFormatHandler.ImageFormatTypes format )

The parameter filename holds the desired name with a complete path, the extension will be substituted depending on the file type selected by the parameter format.

This methods loads some parameters depending on the file format chosen:

ImageCodecInfo info;
EncoderParameters parameters = 
  formatHandler.GetEncoderParameters( format, out info );

That's where we use the helper class ImageFormatHandler which does all that. I think this is a base which can be used for customizing to your own needs.

Changes

The actual example has been updated by some method, which can be used to capture screens from other processes; to do that, native code must be used. Then it is no longer a pure .NET 2.0 solution. We also did not test this solution with layered forms, but a bit of modification in the base capturing method should enable this.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Holzhauer


Member

Occupation: Web Developer
Location: Germany Germany

Other popular General Graphics articles:

  • A flexible charting library for .NET
    Looking for a way to draw 2D line graphs with C#? Here's yet another charting class library with a high degree of configurability, that is also easy to use.
  • CxImage
    CxImage is a C++ class to load, save, display, transform BMP, JPEG, GIF, PNG, TIFF, MNG, ICO, PCX, TGA, WMF, WBMP, JBG, J2K images.
  • 3D Pie Chart
    A class library for drawing 3D pie charts.
  • Barcode Image Generation Library
    This library was designed to give an easy class for developers to use when they need to generate barcode images from a string of data.
  • ImageStone
    An article on a library for image manipulation.
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 42 (Total in Forum: 42) (Refresh)FirstPrevNext
GeneralCapture screen in different ways, object wise, rectangle wise etc. Pinmemberyogesh_softworld1231:52 13 Oct '09  
GeneralThanks PinmemberKennShipley11:21 19 Jun '09  
GeneralJust what I was looking for PinmemberCaptainobvious6:37 29 Sep '08  
Generalabout minimize the window Pinmemberzac_cn119:00 16 Jan '08  
GeneralThanks for your work Pinmembermistnick5:03 11 Jan '08  
QuestionI need the help please Pinmemberaishar7:55 23 Nov '07  
Generalcapture Window with alpha PinmemberGallo_Teo8:26 8 May '07  
GeneralCapturing on local system account Pinmemberbiszkopt6:55 11 Mar '07  
GeneralHow to ... Pinmembersuneel_sp20:03 6 Mar '07  
GeneralAlphablended windows Pinmemberfouloud23:48 9 Dec '06  
Generalexported screen capture function Pinmemberjb70604058:56 26 Sep '06  
AnswerRe: exported screen capture function PinmemberHolzhauer20:56 26 Sep '06  
QuestionCapturing, No problem... but can you draw? PinmemberJohn Storer II17:59 7 Sep '06  
AnswerRe: License Information PinmemberHolzhauer22:03 24 Aug '06  
QuestionLicense Information Pinmembersmartsarna9:26 24 Aug '06  
QuestionRe: License Information PinmemberNikhil_77777:48 13 Feb '09  
GeneralCapture process screen without changing his Z-ORDER Pinmemberasafbenzaken8:25 2 Jul '06  
GeneralCode used in ASP.Net Pinmemberas_mahadevan2:23 31 May '06  
GeneralHow it is possible through ASP.NET Pinmemberas_mahadevan2:15 31 May '06  
GeneralKurzform PinmemberDave305223:19 22 Apr '06  
GeneralCapture MOVIE PinmemberMichael Sync11:35 22 Apr '06  
GeneralVS.Net 2003 PinmemberAhmed.mb7:29 1 Apr '06  
GeneralRe: VS.Net 2003 Pinmemberedy8376:03 15 Aug '06  
Generalnette Arbeit PinmemberThe_Myth23:51 24 Mar '06  
GeneralLayered Windows PinmemberThomassen13:00 23 Mar '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Mar 2006
Editor: Smitha Vijayan
Copyright 2006 by Holzhauer
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project