private static BitmapSource? TryCaptureFullScreen()

in src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/Harness/ScreenshotService.cs [56:101]


        private static BitmapSource? TryCaptureFullScreen()
        {
            var width = Screen.PrimaryScreen.Bounds.Width;
            var height = Screen.PrimaryScreen.Bounds.Height;

            if (width <= 0 || height <= 0)
            {
                // Don't try to take a screenshot if there is no screen.
                // This may not be an interactive session.
                return null;
            }

            using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.CopyFromScreen(
                    sourceX: Screen.PrimaryScreen.Bounds.X,
                    sourceY: Screen.PrimaryScreen.Bounds.Y,
                    destinationX: 0,
                    destinationY: 0,
                    blockRegionSize: bitmap.Size,
                    copyPixelOperation: CopyPixelOperation.SourceCopy);

                var bitmapData = bitmap.LockBits(
                    new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                    ImageLockMode.ReadOnly,
                    PixelFormat.Format32bppArgb);
                try
                {
                    return BitmapSource.Create(
                        bitmapData.Width,
                        bitmapData.Height,
                        bitmap.HorizontalResolution,
                        bitmap.VerticalResolution,
                        PixelFormats.Bgra32,
                        null,
                        bitmapData.Scan0,
                        bitmapData.Stride * bitmapData.Height,
                        bitmapData.Stride);
                }
                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }
            }
        }