c#抓屏
1 public static Bitmap GetDesktopWindowCaptureAsBitmap() 2 { 3 Rectangle rcScreen = Rectangle.Empty; 4 Screen[] screens = Screen.AllScreens; 5 6 7 // Create a rectangle encompassing all screens... 8 foreach(Screen screen in screens) 9 rcScreen = Rectangle.Union(rcScreen, screen.Bounds); 10 11 // Create a composite bitmap of the size of all screens... 12 Bitmap finalBitmap = new Bitmap(rcScreen.Width, rcScreen.Height); 13 14 // Get a graphics object for the composite bitmap and initialize it... 15 Graphics g = Graphics.FromImage(finalBitmap); 16 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; 17 g.FillRectangle( 18 SystemBrushes.Desktop, 19 0, 20 0, 21 rcScreen.Width - rcScreen.X, 22 rcScreen.Height - rcScreen.Y); 23 24 // Get an HDC for the composite area... 25 IntPtr hdcDestination = g.GetHdc(); 26 27 // Now, loop through screens, 28 // Blting each to the composite HDC created above... 29 foreach(Screen screen in screens) 30 { 31 // Create DC for each source monitor... 32 IntPtr hdcSource = Win32.CreateDC( 33 IntPtr.Zero, 34 screen.DeviceName, 35 IntPtr.Zero, 36 IntPtr.Zero); 37 38 // Blt the source directly to the composite destination... 39 int xDest = screen.Bounds.X - rcScreen.X; 40 int yDest = screen.Bounds.Y - rcScreen.Y; 41 42 bool success = Win32.StretchBlt( 43 hdcDestination, 44 xDest, 45 yDest, 46 screen.Bounds.Width, 47 screen.Bounds.Height, 48 hdcSource, 49 0, 50 0, 51 screen.Bounds.Width, 52 screen.Bounds.Height, 53 (int)Win32.TernaryRasterOperations.SRCCOPY); 54 55 // System.Diagnostics.Trace.WriteLine(screen.Bounds); 56 57 if (!success) 58 { 59 System.ComponentModel.Win32Exception win32Exception = 60 new System.ComponentModel.Win32Exception(); 61 System.Diagnostics.Trace.WriteLine(win32Exception); 62 } 63 64 // Cleanup source HDC... 65 Win32.DeleteDC(hdcSource); 66 } 67 68 // Cleanup destination HDC and Graphics... 69 g.ReleaseHdc(hdcDestination); 70 g.Dispose(); 71 72 // IntPtr hDC = GetDC(IntPtr.Zero); 73 // Graphics gDest = Graphics.FromHdc(hDC); 74 // gDest.DrawImage(finalBitmap, 0, 0, 640, 480); 75 // gDest.Dispose(); 76 // ReleaseDC(IntPtr.Zero, hDC); 77 78 // Return composite bitmap which will become our Form's PictureBox's image... 79 return finalBitmap; 80 81 } 82