VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之C#抓取当前屏幕并保存为图片的方法

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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#程序设计有所帮助。


相关教程