public static (Bitmap, CursorPosition?) CaptureScreenshot(Rectangle area, bool captureCursor) { var desktopWindowHandle = GetDesktopWindow(); var source = DeviceContext.FromWindow(desktopWindowHandle); try { using var destination = DeviceContext.CreateCompatible(source); using var bitmap = source.CreateCompatibleBitmap(area.Size); var oldBitmap = destination.SelectObject(bitmap); var destinationRectangle = new Rectangle(0, 0, area.Width, area.Height); destination.BitBlt(destinationRectangle, source, area.Location, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); var cursorInfo = GetCursorInfo(); // Regardless of whether the cursor is visible, we want to return the position CursorPosition?cursorPos = null; if (cursorInfo != null) { var info = cursorInfo.Value; // The coordinates might be negative if the task bar is on the right screen, // so we need to convert the screen coordinates to image coordinates by subtracting the base offset of the cirtual screen var(imageX, imageY) = (info.screenPosX - area.X, info.screenPosY - area.Y); cursorPos = new( new Point(info.screenPosX, info.screenPosY), new Point(imageX, imageY) ); if (captureCursor) { DrawCurrentCursorToImageIfVisible(info, cursorPos.OnImage, destination); } } var screenshot = bitmap.ToImage(); destination.SelectObject(oldBitmap); return(screenshot, cursorPos); } finally { _ = ReleaseDC(desktopWindowHandle, source.DC); } }