Winform屏幕截圖保存C#代碼
代碼如下:
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest, // 目標 DC的句柄
int nXDest,
int nYDest,
int nWidth,
int nHeight,
IntPtr hdcSrc, // 源DC的句柄
int nXSrc,
int nYSrc,
System.Int32 dwRop // 光柵的處理數值
);
private void button1_Click(object sender, System.EventArgs e)
{
//獲得當前屏幕的大小 http://www.cnblogs.com/roucheng/
Rectangle rect = new Rectangle ( ) ;
rect = Screen.GetWorkingArea ( this ) ;
//創建一個以當前屏幕為模板的圖象
Graphics g1 = this.CreateGraphics ( ) ;
//創建以屏幕大小為標准的位圖
Image MyImage = new Bitmap ( rect.Width , rect.Height , g1 ) ;
Graphics g2 = Graphics.FromImage ( MyImage ) ;
//得到屏幕的DC
IntPtr dc1 = g1.GetHdc ( ) ;
//得到Bitmap的DC
IntPtr dc2 = g2.GetHdc ( ) ;
//調用此API函數,實現屏幕捕獲
BitBlt ( dc2 , 0 , 0 , rect.Width , rect.Height , dc1 , 0 , 0 , 13369376 ) ;
//釋放掉屏幕的DC
g1.ReleaseHdc ( dc1 ) ;
//釋放掉Bitmap的DC
g2.ReleaseHdc ( dc2 ) ;
//以JPG文件格式來保存
MyImage.Save ( @"c:/Capture.jpg" , ImageFormat.Jpeg );
MessageBox.Show ( "當前屏幕已經保存為C盤的capture.jpg文件!" ) ;
}