SoFunction
Updated on 2025-03-07

C# How to grab the current screen and save it as a picture

This article example describes how C# grabs the current screen and saves it as a picture. Share it for your reference. The specific analysis is as follows:

This is a C# screen grabber that can grab the entire screen and save the picture in the specified format, and save the current console cache to text

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace RobvanderWoude
{
 class PrintScreen
 {
  static int Main( string[] args )
  {
   try
   {
    string output = ;
    bool overwrite = false;
    bool text = false;
    ImageFormat type = null;
    #region Command Line parsing
    if (  == 0 )
    {
     return WriteError( );
    }
    foreach ( string arg in args )
    {
     switch ( ( ).Substring( 0, 2 ) )
     {
      case "/?":
       return WriteError( );
      case "/O":
       overwrite = true;
       break;
      case "/T":
       if ( text )
       {
        return WriteError( "Cannot capture current window as bitmap" );
       }
       switch ( ( ).Substring( 3 ) )
       {
        case "BMP":
         type = ;
         break;
        case "GIF":
         type = ;
         break;
        case "JPG":
        case "JPEG":
         type = ;
         break;
        case "PNG":
         type = ;
         break;
        case "TIF":
        case "TIFF":
         type = ;
         break;
        case "TXT":
         text = true;
         break;
        default:
         return WriteError( "Invalid file format: \"" + ( 4 ) + "\"" );
       }
       break;
      default:
       output = arg;
       break;
     }
    }
    // Check if directory exists
    if ( !( ( output ) ) )
    {
     return WriteError( "Invalid path for output file: \"" + output + "\"" );
    }
    // Check if file exists, and if so, if it can be overwritten
    if ( ( output ) )
    {
     if ( overwrite )
     {
      ( output );
     }
     else
     {
      return WriteError( "File exists; use /O to overwrite existing files." );
     }
    }
    if ( type == null && text == false )
    {
     string ext = ( output ).ToUpper( );
     switch ( ext )
     {
      case ".BMP":
       type = ;
       break;
      case ".GIF":
       type = ;
       break;
      case ".JPG":
      case ".JPEG":
       type = ;
       break;
      case ".PNG":
       type = ;
       break;
      case ".TIF":
      case ".TIFF":
       type = ;
       break;
      case ".TXT":
       text = true;
       break;
      default:
       return WriteError( "Invalid file type: \"" + ext + "\"" );
       return 1;
     }
    }
    #endregion Command Line parsing
    if ( text )
    {
     string readtext = ;
     for ( short i = 0; i < (short) ; i++ )
     {
      foreach ( string line in ( 0, i, (short) , 1 ) )
      {
       readtext += line + "\n";
      }
     }
     StreamWriter file = new StreamWriter( output );
     ( readtext );
     ( );
    }
    else
    {
     int width = ;
     int height = ;
     int top = 0;
     int left = 0;
     Bitmap printscreen = new Bitmap( width, height );
     Graphics graphics = ( printscreen as Image );
     ( top, left, 0, 0,  );
     ( output, type );
    }
    return 0;
   }
   catch ( Exception e )
   {
    (  );
    return 1;
   }
  }
  #region Error Handling
  public static int WriteError( string errorMessage = "" )
  {
   ( );
   if ( ( errorMessage ) == false )
   {
    ( );
     = ;
    ( "ERROR: " );
     = ;
    ( errorMessage );
    ( );
   }
   ( );
   ( "PrintScreen, Version 1.10" );
   ( "Save a screenshot as image or save the current console buffer as text" );
   ( );
   ( "Usage:  " );
    = ;
   ( "PRINTSCREEN outputfile [ /T:type ] [ /O ]" );
   ( );
   ( );
   ( "Where:  " );
    = ;
   ( "outputfile" );
   ( );
   ( "  is the file to save the screenshot or text to" );
    = ;
   ( "   /T:type" );
   ( );
   ( "  specifies the file type: " );
    = ;
   ( "BMP" );
   ( );
   ( ", " );
    = ;
   ( "GIF" );
   ( );
   ( ", " );
    = ;
   ( "JPG" );
   ( );
   ( ", " );
    = ;
   ( "PNG" );
   ( );
   ( ", " );
    = ;
   ( "TIF" );
   ( );
   ( " or " );
    = ;
   ( "TXT" );
   ( );
   ( "      (only required if " );
    = ;
   ( "outputfile" );
   ( );
   ( " extension is different)" );
    = ;
   ( "   /O" );
   ( );
   ( "    overwrites an existing file" );
   ( );
   ( "Credits: Code to read console buffer by Simon Mourier " );
    = ;
   ( "" );
   ( );
   ( "   Code for graphic screenshot by Ali Hamdar " );
    = ;
   ( "https://" );
   ( );
   ( );
   ( "Written by Rob van der Woude" );
   ( "" );
   return 1;
  }
  #endregion Error Handling
 }
 #region Read From Console Buffer
 public class ConsoleReader
 {
  public static IEnumerable<string> ReadFromBuffer( short x, short y, short width, short height )
  {
   IntPtr buffer = ( width * height * ( typeof( CHAR_INFO ) ) );
   if ( buffer == null )
    throw new OutOfMemoryException( );
   try
   {
    COORD coord = new COORD( );
    SMALL_RECT rc = new SMALL_RECT( );
     = x;
     = y;
     = (short) ( x + width - 1 );
     = (short) ( y + height - 1 );
    COORD size = new COORD( );
     = width;
     = height;
    const int STD_OUTPUT_HANDLE = -11;
    if ( !ReadConsoleOutput( GetStdHandle( STD_OUTPUT_HANDLE ), buffer, size, coord, ref rc ) )
    {
     // 'Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
     throw new Win32Exception( Marshal.GetLastWin32Error( ) );
    }
    IntPtr ptr = buffer;
    for ( int h = 0; h < height; h++ )
    {
     StringBuilder sb = new StringBuilder( );
     for ( int w = 0; w < width; w++ )
     {
      CHAR_INFO ci = (CHAR_INFO) ( ptr, typeof( CHAR_INFO ) );
      char[] chars = (  );
      ( chars[0] );
      ptr += ( typeof( CHAR_INFO ) );
     }
     yield return ( );
    }
   }
   finally
   {
    ( buffer );
   }
  }
  [StructLayout(  )]
  private struct CHAR_INFO
  {
   [MarshalAs( , SizeConst = 2 )]
   public byte[] charData;
   public short attributes;
  }
  [StructLayout(  )]
  private struct COORD
  {
   public short X;
   public short Y;
  }
  [StructLayout(  )]
  private struct SMALL_RECT
  {
   public short Left;
   public short Top;
   public short Right;
   public short Bottom;
  }
  [StructLayout(  )]
  private struct CONSOLE_SCREEN_BUFFER_INFO
  {
   public COORD dwSize;
   public COORD dwCursorPosition;
   public short wAttributes;
   public SMALL_RECT srWindow;
   public COORD dwMaximumWindowSize;
  }
  [DllImport( "", SetLastError = true )]
  private static extern bool ReadConsoleOutput( IntPtr hConsoleOutput, IntPtr lpBuffer, COORD dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT lpReadRegion );
  [DllImport( "", SetLastError = true )]
  private static extern IntPtr GetStdHandle( int nStdHandle );
 }
 #endregion Read From Console Buffer
}

I hope this article will be helpful to everyone's C# programming.