How to Capture Screen using C#.Net

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Linq;  
  5. using System.Runtime.InteropServices;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9. namespace ScreenCapture
  10. {  
  11.     public class ScreenCapture  
  12.     {  
  13.         [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]  
  14.         private static extern IntPtr GetDC(IntPtr hWnd);  
  15.   
  16.         [DllImport("user32.dll", ExactSpelling = true)]  
  17.         private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);  
  18.   
  19.         [DllImport("gdi32.dll", ExactSpelling = true)]  
  20.         private static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);  
  21.   
  22.         [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]  
  23.         private static extern IntPtr GetDesktopWindow();  
  24.   
  25.         /// <summary>  
  26.         /// Capture Screen  
  27.         /// </summary>  
  28.         /// <returns></returns>  
  29.         public static Bitmap Capture()  
  30.         {  
  31.             int screenWidth = Screen.PrimaryScreen.Bounds.Width;  
  32.             int screenHeight = Screen.PrimaryScreen.Bounds.Height;  
  33.   
  34.             Bitmap screenBmp = new Bitmap(screenWidth, screenHeight);  
  35.             Graphics g = Graphics.FromImage(screenBmp);  
  36.   
  37.             IntPtr dc1 = GetDC(GetDesktopWindow());  
  38.             IntPtr dc2 = g.GetHdc();  
  39.   
  40.             BitBlt(dc2, 0, 0, screenWidth, screenHeight, dc1, 0, 0, 13369376);  
  41.   
  42.             ReleaseDC(GetDesktopWindow(), dc1);  
  43.             g.ReleaseHdc(dc2);  
  44.             g.Dispose();  
  45.   
  46.             return screenBmp;  
  47.         }  
  48.     }