C# 截屏类

using System.Runtime.InteropServices;
using System.Drawing;

 1     public class BitMapCaptureScreen
 2     {
 3         [DllImport("GDI32.dll")]
 4         public static extern bool BitBlt(int hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,int hdcSrc,int nXSrc,int nYSrc,int dwRop);
 5         [DllImport("GDI32.dll")]
 6         public static extern int CreateCompatibleBitmap(int hdc, int nWidth, int nHeight);
 7         [DllImport("GDI32.dll")]
 8         public static extern int CreateCompatibleDC(int hdc);
 9         [DllImport("GDI32.dll")]
10         public static extern bool DeleteDC(int hdc);
11         [DllImport("GDI32.dll")]
12         public static extern bool DeleteObject(int hObject);
13         [DllImport("GDI32.dll")]
14         public static extern int GetDeviceCaps(int hdc, int nIndex);
15         [DllImport("GDI32.dll")]
16         public static extern int SelectObject(int hdc, int hgdiobj);
17         [DllImport("User32.dll")]
18         public static extern int GetDesktopWindow();
19         [DllImport("User32.dll")]
20         public static extern int GetWindowDC(int hWnd);
21         [DllImport("User32.dll")]
22         public static extern int ReleaseDC(int hWnd, int hDC);
23 
24         // Captures the current on-screen representation using Windows API calls
25         public Bitmap CaptureScreen()
26         {
27             // Provides a pointer to the visual representation of the desktop window
28             int source = GetWindowDC(GetDesktopWindow());
29             // Secures the image using CreateCompatibleBitmap
30             int bitmap = CreateCompatibleBitmap(source, GetDeviceCaps(source,8), GetDeviceCaps(source,10));
31 
32             int destination = CreateCompatibleDC(source);
33     
34             SelectObject(destination, bitmap);
35             BitBlt(destination,0,0, GetDeviceCaps(source,8), GetDeviceCaps(source,10), source,0,0,0x00CC0020);
36             Bitmap image = GetImage(bitmap);
37             // Save the image as a file.
38             image.Save("c:\\capturescreen.jpg", System.Drawing.Imaging.ImageFormat.Gif);
39             Cleanup(bitmap, source, destination);
40             return image;
41         }
42 
43         private void Cleanup(int bitmap,int source,int destination)
44         {
45             ReleaseDC(GetDesktopWindow(), source);
46             DeleteDC(destination);
47             DeleteObject(bitmap);
48         }
49 
50         private Bitmap GetImage(int hBitmap)
51         {
52             Bitmap image = new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)), Image.FromHbitmap(new IntPtr(hBitmap)).Width,
53             Image.FromHbitmap(new IntPtr(hBitmap)).Height);
54             return image;
55         }
56 
57     }
View Code

 

posted @ 2014-08-13 17:09  壬子木  阅读(199)  评论(0)    收藏  举报