using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace RichCreator.Utility.Captures { public class BitBltCapture:ICapture { /// /// 截屏 /// /// public Bitmap CaptureScreen() { return CaptureWindow(Utils.GetDesktopWindow(),-1,-1,-1,-1); } /// /// 截取指定区域 /// /// /// /// /// /// public Bitmap CaptureScreen(Int32 x,Int32 y,Int32 width,Int32 height) { return CaptureWindow(Utils.GetDesktopWindow(),x,y,width,height); } /// /// Creates an Image object containing a screen shot of a specific window /// /// The handle to the window. (In windows forms, this is obtained by the Handle property) /// private static Bitmap CaptureWindow(IntPtr handle,Int32 x,Int32 y,Int32 width,Int32 height) { //todo:只截取部分的图 // get te hDC of the target window IntPtr hdcSrc = Utils.GetWindowDC(handle); // get the size Utils.Rect rect = new Utils.Rect(); Utils.GetWindowRect(handle, ref rect); int screenWidth = 0; int screenHeight = 0; Utils.GetWindowSize(out screenWidth, out screenHeight); if (x < 0 || y < 0 || width <= 0 || height <= 0 || (x + width) > screenWidth || (y + height) > screenHeight) { x = 0; y = 0; width = screenWidth; height = screenHeight; } // create a device context we can copy to IntPtr hdcDest = Utils.CreateCompatibleDC(hdcSrc); // create a bitmap we can copy it to, // using GetDeviceCaps to get the width/height IntPtr hBitmap = Utils.CreateCompatibleBitmap(hdcSrc, width, height); // select the bitmap object IntPtr hOld = Utils.SelectObject(hdcDest, hBitmap); // bitblt over Utils.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, Utils.SRCCOPY); // restore selection Utils.SelectObject(hdcDest, hOld); // clean up Utils.DeleteDC(hdcDest); Utils.ReleaseDC(handle, hdcSrc); // get a .NET image object for it Bitmap img = Bitmap.FromHbitmap(hBitmap); // free up the Bitmap object Utils.DeleteObject(hBitmap); return img; } /// /// Captures a screen shot of the entire desktop, and saves it to a file /// /// /// public void CaptureScreenToFile(string fileName) { CaptureScreenToFile(fileName, ImageFormat.Jpeg); } /// /// Captures a screen shot of the entire desktop, and saves it to a file /// /// /// public void CaptureScreenToFile(string fileName, ImageFormat format) { Bitmap bitmap = CaptureScreen(); bitmap.Save(fileName, format); } } }