本文实例讲述了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,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#程序设计有所帮助。
总结以上是内存溢出为你收集整理的C#抓取当前屏幕并保存为图片的方法全部内容,希望文章能够帮你解决C#抓取当前屏幕并保存为图片的方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)