在C#中调用API进行截屏
2009-01-12 16:58 yufun 阅读(2876) 评论(0) 编辑 收藏 举报看代码:
需要Reference下面的DLL:
System.Drawing
System.Windows.Forms
WindowBase
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4: using System.Windows;
5: using System.Windows.Forms;
6: using System.Drawing;
7: using System.Runtime.InteropServices;
8:
9: namespace ConsoleApplication1
10: {
11: class Program
12: {
13: [System.Runtime.InteropServices.DllImport("gdi32.dll")]
14: public static extern IntPtr CreateDC(string driver, string device, IntPtr res1, IntPtr res2);
15:
16: public enum TernaryRasterOperations
17: {
18: SRCCOPY = 0x00CC0020, /* dest = source*/
19: SRCPAINT = 0x00EE0086, /* dest = source OR dest*/
20: SRCAND = 0x008800C6, /* dest = source AND dest*/
21: SRCINVERT = 0x00660046, /* dest = source XOR dest*/
22: SRCERASE = 0x00440328, /* dest = source AND (NOT dest )*/
23: NOTSRCCOPY = 0x00330008, /* dest = (NOT source)*/
24: NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */
25: MERGECOPY = 0x00C000CA, /* dest = (source AND pattern)*/
26: MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest*/
27: PATCOPY = 0x00F00021, /* dest = pattern*/
28: PATPAINT = 0x00FB0A09, /* dest = DPSnoo*/
29: PATINVERT = 0x005A0049, /* dest = pattern XOR dest*/
30: DSTINVERT = 0x00550009, /* dest = (NOT dest)*/
31: BLACKNESS = 0x00000042, /* dest = BLACK*/
32: WHITENESS = 0x00FF0062, /* dest = WHITE*/
33: };
34:
35: [DllImport("gdi32.dll")]
36: public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth,
37: int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
38:
39: public static void CaptureDesktop(string sPath)
40: {
41: Rect rect = new Rect();
42: rect.Width = Screen.PrimaryScreen.Bounds.Width;
43: rect.Height = Screen.PrimaryScreen.Bounds.Height;
44:
45: IntPtr dcTmp = CreateDC("DISPLAY", "DISPLAY", (IntPtr)null, (IntPtr)null);
46: Graphics gScreen = Graphics.FromHdc(dcTmp);
47: Bitmap image = new Bitmap((int)(rect.Width), (int)(rect.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
48: Graphics gImage = Graphics.FromImage(image);
49: IntPtr dcImage = gImage.GetHdc();
50: IntPtr dcScreen = gScreen.GetHdc();
51: BitBlt(dcImage, 0, 0, (int)(rect.Width), (int)(rect.Height), dcScreen, (int)(rect.Left), (int)(rect.Top), TernaryRasterOperations.SRCCOPY);
52: gScreen.ReleaseHdc(dcScreen);
53: gImage.ReleaseHdc(dcImage);
54:
55: image.Save(sPath);
56: }
57:
58: static void Main(string[] args)
59: {
60: CaptureDesktop("c:\\1.bmp");
61: }
62: }
63: }