UIElement Screenshot UWP - C#

Viewed 2148

I search in web but I not found any solution to take a screenshot an UI element (in bitmap by example) in UWP - Universal Windows Platform.

1 Answers

You may use Render XAML to bitmap Some Sample Code here:

    // Render to an image at the current system scale and retrieve pixel contents
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(RenderedGrid);
    var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

    var savePicker = new FileSavePicker();
    savePicker.DefaultFileExtension = ".png";
    savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" });
    savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    savePicker.SuggestedFileName = "snapshot.png";

    // Prompt the user to select a file
    var saveFile = await savePicker.PickSaveFileAsync();

    // Verify the user selected a file
    if (saveFile == null)
        return;

    // Encode the image to the selected file on disk
    using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

        encoder.SetPixelData(
            BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            (uint)renderTargetBitmap.PixelWidth,
            (uint)renderTargetBitmap.PixelHeight,
            DisplayInformation.GetForCurrentView().LogicalDpi,
            DisplayInformation.GetForCurrentView().LogicalDpi,
            pixelBuffer.ToArray());

        await encoder.FlushAsync();
    }

Sample Example https://code.msdn.microsoft.com/windowsapps/XAML-render-to-bitmap-dd4f549f

Related