C#将当前屏幕抓取下来保存为图片

C#将当前屏幕抓取下来保存为图片,第1张

概述C#将当前屏幕抓取下来保存为图片

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

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 )                {                    // Based on code by Simon MourIEr (http://www.softfluent.com/)                    // http://stackoverflow.com/questions/12355378/read-from-location-on-console-c-sharp                    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                {                    // Based on code by Ali Hamdar (http://alihamdar.com/)                    // http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/79efecc4-fa6d-4078-afe4-bb1379bb968b                    // Default values for full screen                    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 = "" )        {            /*            PrintScreen,Version 1.00            Save a screenshot as image or save the current console buffer as text             Usage:   PRINTSCREEN  outputfile  [ /T:type ]  [ /O ]             Where:   outputfile   is the file to save the screenshot or text to                     /T:type      specifIEs the file type: BMP,GIF,JPG,PNG,TIF or TXT                                  (only required if outputfile extension is different)                     /O           overwrites an existing file                         Credits: Code to read console buffer by Simon MourIEr http://www.softfluent.com                     Code for graphic screenshot by Ali Hamdar    http://alihamdar.com                         Written by Rob van der Woude            http://www.robvanderwoude.com            */             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.softfluent.com" );            Console.resetcolor( );            Console.Error.Write( "         Code for graphic screenshot by Ali Hamdar    " );            Console.Foregroundcolor = Consolecolor.DarkGray;            Console.Error.Writeline( "http://alihamdar.com" );            Console.resetcolor( );            Console.Error.Writeline( );            Console.Error.Writeline( "Written by Rob van der Woude" );            Console.Error.Writeline( "http://www.robvanderwoude.com" );            return 1;        }        #endregion Error Handling     }     #region Read From Console Buffer     // ConsoleReader by Simon MourIEr (http://www.softfluent.com/)    // http://stackoverflow.com/questions/12355378/read-from-location-on-console-c-sharp    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}

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的C#将当前屏幕抓取下来保存为图片全部内容,希望文章能够帮你解决C#将当前屏幕抓取下来保存为图片所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1238173.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存