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( "http://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#程序设计有所帮助。

(0)

相关推荐

  • ASP.net(C#)从其他网站抓取内容并截取有用信息的实现代码

    1. 需要引用的类库 复制代码 代码如下: using System.Net; using System.IO; using System.Text; using System.Text.RegularExpressions; 2. 获取其他网站网页内容的关键代码 复制代码 代码如下: WebRequest request = WebRequest.Create("http://目标网址.com/"); WebResponse response = request.GetRespons

  • c#实现抓取高清美女妹纸图片

    c#实现抓取高清美女妹纸图片 复制代码 代码如下: private void DoFetch(int pageNum)         {             ThreadPool.QueueUserWorkItem(_ =>             {                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://me2-sex.lofter.com/tag/美女摄影?page=&

  • c# HttpWebRequest通过代理服务器抓取网页内容应用介绍

    内网用户或代理上网的用户使用 复制代码 代码如下: using System.IO; using System.Net; public string get_html() { string urlStr = "http://www.domain.com"; //設定要獲取的地址 HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(urlStr); //建立HttpWebRequest對象 hwr.Timeout = 60

  • asp.net c# 抓取页面信息方法介绍

    一:网页更新 我们知道,一般网页中的信息是不断翻新的,这也要求我们定期的去抓这些新信息,但是这个"定期"该怎么理解,也就是多长时间需要抓一次该页面,其实这个定期也就是页面缓存时间,在页面的缓存时间内我们再次抓取该网页是没有必要的,反而给人家服务器造成压力. 就比如说我要抓取博客园首页,首先清空页面缓存, 从Last-Modified到Expires,我们可以看到,博客园的缓存时间是2分钟,而且我还能看到当前的服务器时间Date,如果我再次 刷新页面的话,这里的Date将会变成下图中 I

  • C# 抓取网页内容的方法

    1.抓取一般内容 需要三个类:WebRequest.WebResponse.StreamReader 所需命名空间:System.Net.System.IO 核心代码: view plaincopy to clipboardprint? 复制代码 代码如下: WebRequest request = WebRequest.Create("http://www.jb51.net/");   WebResponse response = request.GetResponse();   S

  • c#根据网址抓取网页截屏生成图片的示例

    复制代码 代码如下: using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Threading;using System.Windows.Forms; public class WebsiteToImage{private Bitmap m_Bitmap;private string m_Url;private string m_FileName = string.Empty; public

  • C#抓取网页数据 解析标题描述图片等信息 去除HTML标签

    一.首先将网页内容整个抓取下来,数据放在byte[]中(网络上传输时形式是byte),进一步转化为String,以便于对其操作,实例如下: 复制代码 代码如下: private static string GetPageData(string url) {     if (url == null || url.Trim() == "")         return null;     WebClient wc = new WebClient();     wc.Credentials

  • C#使用HtmlAgilityPack抓取糗事百科内容实例

    本文实例讲述了C#使用HtmlAgilityPack抓取糗事百科内容的方法.分享给大家供大家参考.具体实现方法如下: Console.WriteLine("*****************糗事百科24小时热门*******************"); Console.WriteLine("请输入页码,输入0退出"); string page = Console.ReadLine(); while (page!="0") { HtmlWeb h

  • C#实现抓取和分析网页类实例

    本文实例讲述了C#实现抓取和分析网页类.分享给大家供大家参考.具体分析如下: 这里介绍了抓取和分析网页的类. 其主要功能有: 1.提取网页的纯文本,去所有html标签和javascript代码 2.提取网页的链接,包括href和frame及iframe 3.提取网页的title等(其它的标签可依此类推,正则是一样的) 4.可以实现简单的表单提交及cookie保存 /* * Author:Sunjoy at CCNU * 如果您改进了这个类请发一份代码给我(ccnusjy 在gmail.com)

  • 基于C#实现网络爬虫 C#抓取网页Html源码

    最近刚完成一个简单的网络爬虫,开始的时候很迷茫,不知道如何入手,后来发现了很多的资料,不过真正能达到我需要,有用的资料--代码很难找.所以我想发这篇文章让一些要做这个功能的朋友少走一些弯路. 首先是抓取Html源码,并选择<ul class="post_list">  </ul>节点的href:要添加using System.IO;using System.Net; private void Search(string url) { string rl; Web

  • C#实现通过程序自动抓取远程Web网页信息的代码

    通过程序自动的读取其它网站网页显示的信息,类似于爬虫程序.比方说我们有一个系统,要提取BaiDu网站上歌曲搜索排名.分析系统在根据得到的数据进行数据分析.为业务提供参考数据. 为了完成以上的需求,我们就需要模拟浏览器浏览网页,得到页面的数据在进行分析,最后把分析的结构,即整理好的数据写入数据库.那么我们的思路就是: 1.发送HttpRequest请求. 2.接收HttpResponse返回的结果.得到特定页面的html源文件. 3.取出包含数据的那一部分源码. 4.根据html源码生成HtmlD

随机推荐