public static Bitmap CaptureRegion(Rect region) { Bitmap result; // ReSharper disable once IdentifierTypo var desktophWnd = NativeScreenShotMethods.GetDesktopWindow(); var desktopDc = NativeScreenShotMethods.GetWindowDC(desktophWnd); var memoryDc = NativeScreenShotMethods.CreateCompatibleDC(desktopDc); var bitmap = NativeScreenShotMethods.CreateCompatibleBitmap(desktopDc, (int)region.Width, (int)region.Height); var oldBitmap = NativeScreenShotMethods.SelectObject(memoryDc, bitmap); var success = NativeScreenShotMethods.BitBlt(memoryDc, 0, 0, (int)region.Width, (int)region.Height, desktopDc, (int)region.Left, (int)region.Top, NativeScreenShotMethods.RasterOperations.SRCCOPY | NativeScreenShotMethods.RasterOperations.CAPTUREBLT); try { if (!success) { throw new Win32Exception(); } result = Image.FromHbitmap(bitmap); } finally { NativeScreenShotMethods.SelectObject(memoryDc, oldBitmap); NativeScreenShotMethods.DeleteObject(bitmap); NativeScreenShotMethods.DeleteDC(memoryDc); NativeScreenShotMethods.ReleaseDC(desktophWnd, desktopDc); } return(result); }
//https://stackoverflow.com/questions/1118496/using-image-control-in-wpf-to-display-system-drawing-bitmap/1118557#1118557 public static BitmapSource BitmapSourceFromSystemDrawingBitmap(Bitmap source) { var ip = source.GetHbitmap(); BitmapSource bs; try { bs = Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { NativeScreenShotMethods.DeleteObject(ip); } return(bs); }