欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#抓取当前屏幕并保存为图片的方法

程序员文章站 2023-11-06 22:02:58
本文实例讲述了c#抓取当前屏幕并保存为图片的方法。分享给大家供大家参考。具体分析如下: 这是一个c#实现的屏幕抓取程序,可以抓取整个屏幕保存为指定格式的图片,并且保存当前...

本文实例讲述了c#抓取当前屏幕并保存为图片的方法。分享给大家供大家参考。具体分析如下:

这是一个c#实现的屏幕抓取程序,可以抓取整个屏幕保存为指定格式的图片,并且保存当前控制台缓存到文本

using system;
using system.collections.generic;
using system.componentmodel;
using system.diagnostics;
using system.drawing;
using system.drawing.imaging;
using system.io;
using system.runtime.interopservices;
using system.text;
using system.threading;
using system.windows.forms;
namespace robvanderwoude
{
 class printscreen
 {
  static int main( string[] args )
  {
   try
   {
    string output = string.empty;
    bool overwrite = false;
    bool text = false;
    imageformat type = null;
    #region command line parsing
    if ( args.length == 0 )
    {
     return writeerror( );
    }
    foreach ( string arg in args )
    {
     switch ( arg.toupper( ).substring( 0, 2 ) )
     {
      case "/?":
       return writeerror( );
      case "/o":
       overwrite = true;
       break;
      case "/t":
       if ( text )
       {
        return writeerror( "cannot capture current window as bitmap" );
       }
       switch ( arg.toupper( ).substring( 3 ) )
       {
        case "bmp":
         type = imageformat.bmp;
         break;
        case "gif":
         type = imageformat.gif;
         break;
        case "jpg":
        case "jpeg":
         type = imageformat.jpeg;
         break;
        case "png":
         type = imageformat.png;
         break;
        case "tif":
        case "tiff":
         type = imageformat.tiff;
         break;
        case "txt":
         text = true;
         break;
        default:
         return writeerror( "invalid file format: \"" + arg.substring( 4 ) + "\"" );
       }
       break;
      default:
       output = arg;
       break;
     }
    }
    // check if directory exists
    if ( !directory.exists( path.getdirectoryname( output ) ) )
    {
     return writeerror( "invalid path for output file: \"" + output + "\"" );
    }
    // check if file exists, and if so, if it can be overwritten
    if ( file.exists( output ) )
    {
     if ( overwrite )
     {
      file.delete( output );
     }
     else
     {
      return writeerror( "file exists; use /o to overwrite existing files." );
     }
    }
    if ( type == null && text == false )
    {
     string ext = path.getextension( output ).toupper( );
     switch ( ext )
     {
      case ".bmp":
       type = imageformat.bmp;
       break;
      case ".gif":
       type = imageformat.gif;
       break;
      case ".jpg":
      case ".jpeg":
       type = imageformat.jpeg;
       break;
      case ".png":
       type = imageformat.png;
       break;
      case ".tif":
      case ".tiff":
       type = imageformat.tiff;
       break;
      case ".txt":
       text = true;
       break;
      default:
       return writeerror( "invalid file type: \"" + ext + "\"" );
       return 1;
     }
    }
    #endregion command line parsing
    if ( text )
    {
     string readtext = string.empty;
     for ( short i = 0; i < (short) console.bufferheight; i++ )
     {
      foreach ( string line in consolereader.readfrombuffer( 0, i, (short) console.bufferwidth, 1 ) )
      {
       readtext += line + "\n";
      }
     }
     streamwriter file = new streamwriter( output );
     file.write( readtext );
     file.close( );
    }
    else
    {
     int width = screen.primaryscreen.bounds.width;
     int height = screen.primaryscreen.bounds.height;
     int top = 0;
     int left = 0;
     bitmap printscreen = new bitmap( width, height );
     graphics graphics = graphics.fromimage( printscreen as image );
     graphics.copyfromscreen( top, left, 0, 0, printscreen.size );
     printscreen.save( output, type );
    }
    return 0;
   }
   catch ( exception e )
   {
    console.error.writeline( e.message );
    return 1;
   }
  }
  #region error handling
  public static int writeerror( string errormessage = "" )
  {
   console.resetcolor( );
   if ( string.isnullorempty( errormessage ) == false )
   {
    console.error.writeline( );
    console.foregroundcolor = consolecolor.red;
    console.error.write( "error: " );
    console.foregroundcolor = consolecolor.white;
    console.error.writeline( errormessage );
    console.resetcolor( );
   }
   console.error.writeline( );
   console.error.writeline( "printscreen, version 1.10" );
   console.error.writeline( "save a screenshot as image or save the current console buffer as text" );
   console.error.writeline( );
   console.error.write( "usage:  " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "printscreen outputfile [ /t:type ] [ /o ]" );
   console.resetcolor( );
   console.error.writeline( );
   console.error.write( "where:  " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "outputfile" );
   console.resetcolor( );
   console.error.writeline( "  is the file to save the screenshot or text to" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "   /t:type" );
   console.resetcolor( );
   console.error.write( "  specifies the file type: " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "bmp" );
   console.resetcolor( );
   console.error.write( ", " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "gif" );
   console.resetcolor( );
   console.error.write( ", " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "jpg" );
   console.resetcolor( );
   console.error.write( ", " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "png" );
   console.resetcolor( );
   console.error.write( ", " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "tif" );
   console.resetcolor( );
   console.error.write( " or " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "txt" );
   console.resetcolor( );
   console.error.write( "      (only required if " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "outputfile" );
   console.resetcolor( );
   console.error.writeline( " extension is different)" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "   /o" );
   console.resetcolor( );
   console.error.writeline( "    overwrites an existing file" );
   console.error.writeline( );
   console.error.write( "credits: code to read console buffer by simon mourier " );
   console.foregroundcolor = consolecolor.darkgray;
   console.error.writeline( "http://www.sina.com.cn" );
   console.resetcolor( );
   console.error.write( "   code for graphic screenshot by ali hamdar " );
   console.foregroundcolor = consolecolor.darkgray;
   console.error.writeline( "//www.jb51.net" );
   console.resetcolor( );
   console.error.writeline( );
   console.error.writeline( "written by rob van der woude" );
   console.error.writeline( "http://www.qq.com" );
   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 = marshal.allochglobal( width * height * marshal.sizeof( typeof( char_info ) ) );
   if ( buffer == null )
    throw new outofmemoryexception( );
   try
   {
    coord coord = new coord( );
    small_rect rc = new small_rect( );
    rc.left = x;
    rc.top = y;
    rc.right = (short) ( x + width - 1 );
    rc.bottom = (short) ( y + height - 1 );
    coord size = new coord( );
    size.x = width;
    size.y = 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) marshal.ptrtostructure( ptr, typeof( char_info ) );
      char[] chars = console.outputencoding.getchars( ci.chardata );
      sb.append( chars[0] );
      ptr += marshal.sizeof( typeof( char_info ) );
     }
     yield return sb.tostring( );
    }
   }
   finally
   {
    marshal.freehglobal( buffer );
   }
  }
  [structlayout( layoutkind.sequential )]
  private struct char_info
  {
   [marshalas( unmanagedtype.byvalarray, sizeconst = 2 )]
   public byte[] chardata;
   public short attributes;
  }
  [structlayout( layoutkind.sequential )]
  private struct coord
  {
   public short x;
   public short y;
  }
  [structlayout( layoutkind.sequential )]
  private struct small_rect
  {
   public short left;
   public short top;
   public short right;
   public short bottom;
  }
  [structlayout( layoutkind.sequential )]
  private struct console_screen_buffer_info
  {
   public coord dwsize;
   public coord dwcursorposition;
   public short wattributes;
   public small_rect srwindow;
   public coord dwmaximumwindowsize;
  }
  [dllimport( "kernel32.dll", setlasterror = true )]
  private static extern bool readconsoleoutput( intptr hconsoleoutput, intptr lpbuffer, coord dwbuffersize, coord dwbuffercoord, ref small_rect lpreadregion );
  [dllimport( "kernel32.dll", setlasterror = true )]
  private static extern intptr getstdhandle( int nstdhandle );
 }
 #endregion read from console buffer
}

希望本文所述对大家的c#程序设计有所帮助。