1: public static class ScreenCapture
2: {
3: public static WriteableBitmap GetDesktopImage()
4: {
5: WriteableBitmap bmap = null;
6:
7: // initialize unmanager pointers
8: IntPtr hDC = IntPtr.Zero,
9: hMemDC = IntPtr.Zero,
10: desktop = IntPtr.Zero;
11:
12: try
13: {
14: // get a reference to desktop
15: desktop = User32.GetDesktopWindow();
16: // get an handle to Device Context
17: hDC = User32.GetDC(desktop);
18: // create a new Device Context in memory
19: hMemDC = Gdi32.CreateCompatibleDC(hDC);
20:
21: // read size of desktop window
22: Size size = new Size
23: {
24: Width = User32.GetSystemMetrics(Gdi32.SM_CXSCREEN),
25: Height = User32.GetSystemMetrics(Gdi32.SM_CYSCREEN)
26: };
27:
28: // create a bitmap compatible with desktop
29: IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hDC, size.Width, size.Height);
30:
31: if (hBitmap != IntPtr.Zero)
32: {
33: // select memory Device Context into the new bitmap
34: IntPtr hOld = (IntPtr)Gdi32.SelectObject(hMemDC, hBitmap);
35:
36: // copy the desktop to the memory handle
37: Gdi32.BitBlt(hMemDC, 0, 0, size.Width, size.Height, hDC, 0, 0, (int)TernaryRasterOperations.SRCCOPY);
38:
39: // select the memory Device Context into the bitmap
40: Gdi32.SelectObject(hMemDC, hOld);
41:
42: // initialize a bitmap info
43: BitmapInfo bi = new BitmapInfo
44: {
45: biSize = Marshal.SizeOf(typeof (BitmapInfo)),
46: biWidth = size.Width,
47: biHeight = size.Height,
48: biPlanes = 1,
49: biBitCount = 32,
50: biCompression = 0,
51: biSizeImage = 0,
52: biXPelsPerMeter = 0,
53: biYPelsPerMeter = 0,
54: biClrUsed = 0,
55: biClrImportant = 0
56: };
57:
58: // calculate byte size of the area
59: int dwBmpSize = ((size.Width * bi.biBitCount + 31) / 32) * 4 * size.Height;
60: byte[] data = new byte[dwBmpSize];
61:
62: // initialize a WriteableBitmap to output the result
63: bmap = new WriteableBitmap(size.Width, size.Height);
64:
65: // copy bitmap to byte array
66: Gdi32.GetDIBits(hMemDC, hBitmap, 0, (uint)size.Height, data, ref bi, 0);
67:
68: // compy byte array to WriteableBitmap
69: for (int i = 0; i < data.Length; i += 4)
70: {
71: int y = size.Height - ((i / 4) / size.Width) - 1;
72: int x = (i / 4) % size.Width;
73: int pixel = data[i + 0] | (data[i + 1] << 8) | (data[i + 2] << 16) | (data[i + 3] << 24);
74: bmap.Pixels[y * size.Width + x] = pixel;
75: }
76: }
77: }
78: finally
79: {
80: // release unmanaged resources
81: if (hMemDC != IntPtr.Zero)
82: Gdi32.DeleteDC(hMemDC);
83: if (hDC != IntPtr.Zero)
84: User32.ReleaseDC(desktop, hDC);
85: }
86:
87: // return bitmap
88: return bmap;
89: }
90: }