导入函数
[System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" )]
public static extern bool BitBlt(
IntPtr hdcDest ,
int nXDest ,
int nYDest ,
int nWidth ,
int nHeight ,
IntPtr hdcSrc ,
int nXSrc ,
int nYSrc ,
System.Int32 dwRop
) ;
[System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" )]
public static extern bool StretchBlt(
IntPtr hDC,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hSrcDC,
int xSrc,
int ySrc,
int nSrcWidth,
int nSrcHeight,
System.Int32 dwRop);
[System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" )]
public static extern IntPtr CreateDC (
string lpszDriver,
string lpszDevice,
string lpszOutput,
IntPtr lpInitData
);
[System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" )]
public static extern bool DeleteDC (
IntPtr lpszDriver
);
抓取函数
public static byte[] CaptureDisplay()
{
//define variable
IntPtr dcDisplay;
IntPtr dcImage;
Graphics gDisplay;
Graphics gImage;
System.IO.Stream sImage;
Image imgDisplay;
byte[] bufTemp;
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameter myEncoderParameter1;
EncoderParameters myEncoderParameters;
try
{
//init variable
sImage=new System.IO.MemoryStream();
//get display dc
dcDisplay= WIN32Api.CreateDC("DISPLAY",null, null, IntPtr.Zero);
gDisplay=Graphics.FromHdc(dcDisplay);
//create image
imgDisplay = new Bitmap((int)(gDisplay.VisibleClipBounds.Width) ,(int)(gDisplay.VisibleClipBounds.Height));
gImage = Graphics.FromImage(imgDisplay);
//get image hdc
dcImage = gImage.GetHdc();
//print display to image
WIN32Api.StretchBlt( dcImage, 0, 0, (int)(gDisplay.VisibleClipBounds.Width) ,(int)(gDisplay.VisibleClipBounds.Height ), dcDisplay,0,0,Convert.ToInt32(gDisplay.VisibleClipBounds.Width),Convert.ToInt32(gDisplay.VisibleClipBounds.Height), 13369376);
//release hdc
gImage.ReleaseHdc(dcImage);
WIN32Api.DeleteDC(dcDisplay);
//encode image
myImageCodecInfo=null;
foreach(ImageCodecInfo imagecodecinfo in ImageCodecInfo.GetImageEncoders())
{
if(imagecodecinfo.MimeType=="image/jpeg")
{
myImageCodecInfo=imagecodecinfo;
break;
}
}
//encoder image
//adjust color depth
myEncoderParameters=new EncoderParameters(2);
myEncoder=Encoder.ColorDepth;
myEncoderParameter=new EncoderParameter(myEncoder,8L);
myEncoderParameters.Param[0]=myEncoderParameter;
myEncoder=Encoder.Quality;
myEncoderParameter1=new EncoderParameter(myEncoder,25L);
myEncoderParameters.Param[1]=myEncoderParameter1;
//save image to memory stream
imgDisplay.Save(sImage,myImageCodecInfo,myEncoderParameters);
bufTemp=new byte[sImage.Length];
sImage.Position=0;
sImage.Read(bufTemp,0,bufTemp.Length);
return bufTemp;
}
catch(Exception exp)
{
throw exp;
}
}