1 public static Bitmap GetDesktopImage(bool cursorDisplay = false) 2 { 3 //In size variable we shall keep the size of the screen. 4 Size size = new Size(); 5 //Variable to keep the handle to bitmap. 6 int hBitmap; 7 //Here we get the handle to the desktop device context. 8 int hDC = GetDC(GetDesktopWindow()); 9 //Here we make a compatible device context in memory for screen device context. 10 int hMemDC = CreateCompatibleDC(hDC); 11 // We pass SM_CXSCREEN constant to GetSystemMetrics to get the X coordinates of screen. 12 size.Width = GetSystemMetrics(SM_CXSCREEN); 13 //We pass SM_CYSCREEN constant to GetSystemMetrics to get the Y coordinates of screen. 14 size.Height = GetSystemMetrics(SM_CYSCREEN); 15 //We create a compatible bitmap of screen size using screen device context. 16 hBitmap = CreateCompatibleBitmap(hDC, size.Width, size.Height); 17 //As hBitmap is IntPtr we can not check it against null. For this purspose IntPtr.Zero is used. 18 if (hBitmap != 0) 19 { 20 //Here we select the compatible bitmap in memeory device context and keeps the refrence to Old bitmap. 21 int hOld = SelectObject(hMemDC, hBitmap); 22 //We copy the Bitmap to the memory device context. 23 BitBlt(hMemDC, 0, 0, size.Width, size.Height, hDC, 0, 0, (int)(TernaryRasterOperations.SRCCOPY | TernaryRasterOperations.CaptureBlt)); 24 //We select the old bitmap back to the memory device context. 25 SelectObject(hMemDC, hOld); 26 //We delete the memory device context. 27 DeleteDC(hMemDC); 28 //We release the screen device context. 29 ReleaseDC(GetDesktopWindow(), hDC); 30 //Image is created by Image bitmap handle and stored in local variable. 31 Bitmap bmp = System.Drawing.Image.FromHbitmap((IntPtr)hBitmap); 32 //Release the memory to avoid memory leaks. 33 DeleteObject(hBitmap); 34 35 // 画鼠标 36 if (cursorDisplay) 37 { 38 using (Graphics graphics = Graphics.FromImage(bmp)) 39 { 40 graphics.CompositingQuality = CompositingQuality.HighSpeed; 41 graphics.SmoothingMode = SmoothingMode.HighQuality; 42 //graphics.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(width, height)); 43 44 //显示鼠标 45 DrawMouse(graphics); 46 } 47 } 48 49 //This statement runs the garbage collector manually. 50 //GC.Collect(); 51 //Return the bitmap 52 return bmp; 53 } 54 // If hBitmap is null retunrn null. 55 return null; 56 }
上面这段代码为C#后台抓取屏幕代码,此种方法可以截取到设置为透明的窗里,但是现在有个问题,截屏时,鼠标有点闪烁,有那位大神帮忙看下有那个地方可以改进下?