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

 更新时间:2020年6月25日 11:31  点击:2135

本文实例讲述了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( "https://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#程序设计有所帮助。

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Photoshop古装美女图片转为工笔画效果制作教程

    今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25