8

Looking to modify the following to take a screenshot off all monitors. I have tried adapting it but my images are blank. Writing it to test.png is for testing. The byte[] will be sent to the receiving app.

public byte[] Take()
{
    int screenWidth = Convert.ToInt32(SystemParameters.VirtualScreenWidth);
    int screenHeight = Convert.ToInt32(SystemParameters.VirtualScreenHeight);
    int screenLeft = Convert.ToInt32(SystemParameters.VirtualScreenLeft);
    int screenTop = Convert.ToInt32(SystemParameters.VirtualScreenTop);

    RenderTargetBitmap renderTarget = new RenderTargetBitmap(screenWidth, screenHeight, 96, 96, PixelFormats.Pbgra32);
    VisualBrush sourceBrush = new VisualBrush();

    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();

    using (drawingContext)
    {
        drawingContext.PushTransform(new ScaleTransform(1, 1));
        drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(screenWidth, screenHeight)));
    }
    renderTarget.Render(drawingVisual);

    PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
    pngEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

    Byte[] _imageArray;

    using (MemoryStream outputStream = new MemoryStream())
    {
        pngEncoder.Save(outputStream);
        _imageArray = outputStream.ToArray();
    }

    using (FileStream stream = new FileStream(@"c:\test.png", FileMode.Create, FileAccess.ReadWrite))
    {
        using (BinaryWriter writer = new BinaryWriter(stream))
        {
            writer.Write(_imageArray);
        }
    }

    return _imageArray;
}

2 Answers 2

12

First you'll need to add references for the following namespaces:

using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

Then enumerate your monitors to get the bounding rectangle for all display surfaces and pass that in to the Graphics.CopyFromScreen() method call:

private static BitmapSource CopyScreen()
{
    var left = Screen.AllScreens.Min(screen => screen.Bounds.X);
    var top = Screen.AllScreens.Min(screen => screen.Bounds.Y);
    var right = Screen.AllScreens.Max(screen => screen.Bounds.X + screen.Bounds.Width);
    var bottom = Screen.AllScreens.Max(screen => screen.Bounds.Y + screen.Bounds.Height);
    var width = right - left;
    var height = bottom - top;

    using (var screenBmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
    {
        using (var bmpGraphics = Graphics.FromImage(screenBmp))
        {
            bmpGraphics.CopyFromScreen(left, top, 0, 0, new System.Drawing.Size(width, height));
            return Imaging.CreateBitmapSourceFromHBitmap(
                screenBmp.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
    }
}

Bear in mind though that monitors often don't fit neatly into a single rectangle, particularly if they have different resolution etc, so you might be better snap-shotting the individual screens. Either way, the solution to your problem is to change the coordinates that you were passing in to the Graphics.CopyFromScreen() method call.

EDIT: see Demetris Leptos's comment below, the code I've posted in this answer should be calling DeleteObject on the bitmap returned by screenBmp.GetHbitmap() so as to avoid a memory leak, as specified in the MSDN documentation.

8
  • is there a way to grab each screen as separate capture
    – Tsukasa
    Commented Dec 5, 2013 at 0:16
  • 2
    Absolutely, just enumerate each screen and pass the rectangle {Bounds.X, Bounds.Y, Bounds.X+Bounds.Width, Bounds.Y+Bounds.Height} in as the source rectangle. If you look at the first 4 lines of my code above you'll see I was just creating a rectangle that bounded all of them. Commented Dec 5, 2013 at 1:02
  • Isn't there a way without using Windows.Forms? I might as well not use WPF if I have to use Windows.Forms as a reference.
    – McoreD
    Commented Feb 22, 2016 at 22:48
  • 1
    @McoreD no, WPF is used for the presentation of graphics, hence the 'P'. It also uses the DirectX API, which is separate to the GDI API that forms the core interface to the Windows rendering subsystem. Commented Feb 22, 2016 at 23:08
  • 3
    possible memory leak - posting before I forget to and get lost back into the code: // your code using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000)) { IntPtr hBitmap = bmp.GetHbitmap(); try { var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap) } } from: stackoverflow.com/questions/1546091/… Commented Dec 25, 2016 at 21:09
0

Just to collate the above answers and comments into a single static class with all the includes and imports needed. Tried it with memory profiler and didn't see any leaks.

Use with BitmapSource bmpSource = ScreenCapture.GetBitmapSource();

using System;
using System.Linq;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Windows;

namespace GraphicUtils
{

    public static class ScreenCapture
    {
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);

        public static BitmapSource GetBitmapSource()
        {
            BitmapSource result = null;
            var left = Screen.AllScreens.Min(screen => screen.Bounds.X);
            var top = Screen.AllScreens.Min(screen => screen.Bounds.Y);
            var right = Screen.AllScreens.Max(screen => screen.Bounds.X + screen.Bounds.Width);
            var bottom = Screen.AllScreens.Max(screen => screen.Bounds.Y + screen.Bounds.Height);
            var width = right - left;
            var height = bottom - top;

            using (var screenBmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                using (var bmpGraphics = System.Drawing.Graphics.FromImage(screenBmp))
                {
                    bmpGraphics.CopyFromScreen(left, top, 0, 0, new System.Drawing.Size(width, height));
                    IntPtr hBitmap = screenBmp.GetHbitmap();
                    try
                    {
                        result = Imaging.CreateBitmapSourceFromHBitmap(
                                            hBitmap, IntPtr.Zero, Int32Rect.Empty,
                                            BitmapSizeOptions.FromEmptyOptions());
                    }
                    finally
                    {
                        DeleteObject(hBitmap);
                    }
                }
            }
            return result;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.