Search code examples
pixelsense

How to make a screenshot from the Microsoft Surface emulator?


In order to write a user manual for my application, I need to take some screenshots from the Microsoft Surface emulator.

How can I do that? For sure I could just make a screenshot in my OS and then cut the image in a photo editor, but isn't there a simpler way?


Solution

  • So finally I found a nice way to do it:

    class ScreenshotTaker
        {
            public static void TakeScreenshot(Visual target)
            {
                String fileName = "Screenshot-" + DateTime.UtcNow.ToString().Replace(" ", "-").Replace(".", "_").Replace(":", "_") + ".tiff";
                Console.WriteLine("Try to take screenshot: " + fileName);
                FileStream stream = new FileStream(fileName, FileMode.Create);
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(GetScreenShot(target)));
                encoder.Save(stream);
                stream.Flush();
                stream.Close();
                Console.WriteLine("Screenshot taken");
            }
    
            private static BitmapSource GetScreenShot(Visual target)
            {
                Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
                RenderTargetBitmap bitmap = new RenderTargetBitmap(1024, 768, 96, 96, PixelFormats.Pbgra32);
    
                DrawingVisual drawingvisual = new DrawingVisual();
    
                using (DrawingContext context = drawingvisual.RenderOpen())
                {
                    context.DrawRectangle(new VisualBrush(target), null, new Rect(new Point(), bounds.Size));
                    context.Close();
                }
    
                bitmap.Render(drawingvisual);
                return bitmap;
            }
    
        }