public static Bitmap CaptureDesktop() { Bitmap bmp = null; { var hDc = IntPtr.Zero; try { SIZE size; hDc = Win32.GetDC(Win32.GetDesktopWindow()); var hMemDc = Gdi.CreateCompatibleDC(hDc); size.Cx = Win32.GetSystemMetrics (Win32.SmCxscreen); size.Cy = Win32.GetSystemMetrics (Win32.SmCyscreen); var hBitmap = Gdi.CreateCompatibleBitmap(hDc, size.Cx, size.Cy); if (hBitmap != IntPtr.Zero) { var hOld = Gdi.SelectObject (hMemDc, hBitmap); Gdi.BitBlt(hMemDc, 0, 0, size.Cx, size.Cy, hDc, 0, 0, Gdi.Srccopy); Gdi.SelectObject(hMemDc, hOld); Gdi.DeleteDC(hMemDc); bmp = Image.FromHbitmap(hBitmap); Gdi.DeleteObject(hBitmap); // GC.Collect(); } } finally { if (hDc != IntPtr.Zero) { Win32.ReleaseDC(Win32.GetDesktopWindow(), hDc); } } } return(bmp); }
private void Init() { _windowDC = User.GetWindowDC(_windowHandle); // hdcSys _compatDC = Gdi.CreateCompatibleDC(_windowDC); // hdcMem BITMAPINFO bi = new BITMAPINFO(); bi.bmiHeader.Init(); bi.bmiHeader.biWidth = _rc.Width; bi.bmiHeader.biHeight = -_rc.Height; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; _bitmap = Gdi.CreateDIBSection(_windowDC, ref bi, DIBColors.DIB_RGB_COLORS, out _bitmapPixels, IntPtr.Zero, 0); IntPtr hOldBmp = Gdi.SelectObject(_compatDC, _bitmap); Gdi.DeleteObject(hOldBmp); _mat = new Image <Bgra, byte>(_rc.Width, _rc.Height, 0, _bitmapPixels); }