C#抓取当前屏幕并保存为图片的方法
本文实例讲述了C#抓取当前屏幕并保存为图片的方法。分享给大家供大家参考。具体分析如下:
这是一个C#实现的屏幕抓取程序,可以抓取整个屏幕保存为指定格式的图片,并且保存当前控制台缓存到文本
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Diagnostics;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Windows.Forms;
namespaceRobvanderWoude
{
classPrintScreen
{
staticintMain(string[]args)
{
try
{
stringoutput=string.Empty;
booloverwrite=false;
booltext=false;
ImageFormattype=null;
#regionCommandLineparsing
if(args.Length==0)
{
returnWriteError();
}
foreach(stringarginargs)
{
switch(arg.ToUpper().Substring(0,2))
{
case"/?":
returnWriteError();
case"/O":
overwrite=true;
break;
case"/T":
if(text)
{
returnWriteError("Cannotcapturecurrentwindowasbitmap");
}
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:
returnWriteError("Invalidfileformat:\""+arg.Substring(4)+"\"");
}
break;
default:
output=arg;
break;
}
}
//Checkifdirectoryexists
if(!Directory.Exists(Path.GetDirectoryName(output)))
{
returnWriteError("Invalidpathforoutputfile:\""+output+"\"");
}
//Checkiffileexists,andifso,ifitcanbeoverwritten
if(File.Exists(output))
{
if(overwrite)
{
File.Delete(output);
}
else
{
returnWriteError("Fileexists;use/Otooverwriteexistingfiles.");
}
}
if(type==null&&text==false)
{
stringext=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:
returnWriteError("Invalidfiletype:\""+ext+"\"");
return1;
}
}
#endregionCommandLineparsing
if(text)
{
stringreadtext=string.Empty;
for(shorti=0;i<(short)Console.BufferHeight;i++)
{
foreach(stringlineinConsoleReader.ReadFromBuffer(0,i,(short)Console.BufferWidth,1))
{
readtext+=line+"\n";
}
}
StreamWriterfile=newStreamWriter(output);
file.Write(readtext);
file.Close();
}
else
{
intwidth=Screen.PrimaryScreen.Bounds.Width;
intheight=Screen.PrimaryScreen.Bounds.Height;
inttop=0;
intleft=0;
Bitmapprintscreen=newBitmap(width,height);
Graphicsgraphics=Graphics.FromImage(printscreenasImage);
graphics.CopyFromScreen(top,left,0,0,printscreen.Size);
printscreen.Save(output,type);
}
return0;
}
catch(Exceptione)
{
Console.Error.WriteLine(e.Message);
return1;
}
}
#regionErrorHandling
publicstaticintWriteError(stringerrorMessage="")
{
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,Version1.10");
Console.Error.WriteLine("Saveascreenshotasimageorsavethecurrentconsolebufferastext");
Console.Error.WriteLine();
Console.Error.Write("Usage:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("PRINTSCREENoutputfile[/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("isthefiletosavethescreenshotortextto");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/T:type");
Console.ResetColor();
Console.Error.Write("specifiesthefiletype:");
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("(onlyrequiredif");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("outputfile");
Console.ResetColor();
Console.Error.WriteLine("extensionisdifferent)");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/O");
Console.ResetColor();
Console.Error.WriteLine("overwritesanexistingfile");
Console.Error.WriteLine();
Console.Error.Write("Credits:CodetoreadconsolebufferbySimonMourier");
Console.ForegroundColor=ConsoleColor.DarkGray;
Console.Error.WriteLine("http://www.sina.com.cn");
Console.ResetColor();
Console.Error.Write("CodeforgraphicscreenshotbyAliHamdar");
Console.ForegroundColor=ConsoleColor.DarkGray;
Console.Error.WriteLine("https://www.nhooo.com");
Console.ResetColor();
Console.Error.WriteLine();
Console.Error.WriteLine("WrittenbyRobvanderWoude");
Console.Error.WriteLine("http://www.qq.com");
return1;
}
#endregionErrorHandling
}
#regionReadFromConsoleBuffer
publicclassConsoleReader
{
publicstaticIEnumerable<string>ReadFromBuffer(shortx,shorty,shortwidth,shortheight)
{
IntPtrbuffer=Marshal.AllocHGlobal(width*height*Marshal.SizeOf(typeof(CHAR_INFO)));
if(buffer==null)
thrownewOutOfMemoryException();
try
{
COORDcoord=newCOORD();
SMALL_RECTrc=newSMALL_RECT();
rc.Left=x;
rc.Top=y;
rc.Right=(short)(x+width-1);
rc.Bottom=(short)(y+height-1);
COORDsize=newCOORD();
size.X=width;
size.Y=height;
constintSTD_OUTPUT_HANDLE=-11;
if(!ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),buffer,size,coord,refrc))
{
//'Notenoughstorageisavailabletoprocessthiscommand'mayberaisedforbuffersize>64K(seeReadConsoleOutputdoc.)
thrownewWin32Exception(Marshal.GetLastWin32Error());
}
IntPtrptr=buffer;
for(inth=0;h<height;h++)
{
StringBuildersb=newStringBuilder();
for(intw=0;w<width;w++)
{
CHAR_INFOci=(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));
}
yieldreturnsb.ToString();
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
[StructLayout(LayoutKind.Sequential)]
privatestructCHAR_INFO
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=2)]
publicbyte[]charData;
publicshortattributes;
}
[StructLayout(LayoutKind.Sequential)]
privatestructCOORD
{
publicshortX;
publicshortY;
}
[StructLayout(LayoutKind.Sequential)]
privatestructSMALL_RECT
{
publicshortLeft;
publicshortTop;
publicshortRight;
publicshortBottom;
}
[StructLayout(LayoutKind.Sequential)]
privatestructCONSOLE_SCREEN_BUFFER_INFO
{
publicCOORDdwSize;
publicCOORDdwCursorPosition;
publicshortwAttributes;
publicSMALL_RECTsrWindow;
publicCOORDdwMaximumWindowSize;
}
[DllImport("kernel32.dll",SetLastError=true)]
privatestaticexternboolReadConsoleOutput(IntPtrhConsoleOutput,IntPtrlpBuffer,COORDdwBufferSize,COORDdwBufferCoord,refSMALL_RECTlpReadRegion);
[DllImport("kernel32.dll",SetLastError=true)]
privatestaticexternIntPtrGetStdHandle(intnStdHandle);
}
#endregionReadFromConsoleBuffer
}
希望本文所述对大家的C#程序设计有所帮助。