Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture screen programatically in windows phone 8.1 SDK?

Any Idea how to capture screen in SDK 8.1 windows phone from code? For windows phone 7.5 i have seen the code and tried to use, but it failed. :(

like image 584
greatmajestics Avatar asked May 27 '14 20:05

greatmajestics


2 Answers

You can use a RenderTargetBitmap and pass it a FrameworkElement that represents the page and then render a bitmap from that.

private async Task<RenderTargetBitmap> CreateBitmapFromElement(FrameworkElement uielement)
{
    try
    {
        var renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(uielement);

        return renderTargetBitmap;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex);
    }

    return null;
}

try something like:

private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    this.imagePreview.Source = await CreateBitmapFromElement(this);
}

where the XAML on your page is:

<Grid x:Name="controlsGrid">
    <Button Click="ButtonBase_OnClick">take screenshot</Button>
    <Image x:Name="imagePreview"
           Height="200" VerticalAlignment="Bottom"
           Stretch="UniformToFill" />
</Grid>
like image 156
Matt Lacey Avatar answered Nov 15 '22 00:11

Matt Lacey


To save the rendered image as an image file, we have to send it to a stream, encode it to the file type we want.

This is a method we can use for that (It takes in a UI element, a stream and a Guid):

//Creates RenderTargetBitmap from UI Element 
 async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
  {
      try
      {
          var renderTargetBitmap = new RenderTargetBitmap();
          await renderTargetBitmap.RenderAsync(uielement);
          var pixels = await renderTargetBitmap.GetPixelsAsync();
          var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
          var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
          encoder.SetPixelData(
              BitmapPixelFormat.Bgra8,
              BitmapAlphaMode.Ignore,
              (uint)renderTargetBitmap.PixelWidth,
              (uint)renderTargetBitmap.PixelHeight,
              logicalDpi,
              logicalDpi,
              pixels.ToArray());

          await encoder.FlushAsync();
          return renderTargetBitmap;        
  }

We can then use the FileSavePicker class on Windows Phone 8.1 to decide the filetype, name and saving location.

void CreateFileSavePicker()
    {
        //Create the picker object
        FileSavePicker savePicker = new FileSavePicker();

        // Dropdown of file types the user can save the file as   
        savePicker.FileTypeChoices.Add
            (
            "Image", new List<string>() { ".jpg" });
        // Default file name if the user does not type one in or select // a file to replace
        savePicker.SuggestedFileName = "Screenshot";
        savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; 

        //// Open the picker for the user to pick a file
        savePicker.ContinuationData["Operation"] = "SomeDataOrOther";
        savePicker.PickSaveFileAndContinue();

    }

When the user has picked the file location, it comes back to ContinueFileSavePicker.

public async void      ContinueFileSavePicker(Windows.ApplicationModel.Activation.FileSavePickerContinu ationEventArgs args)
 {
        StorageFile file = args.File;
        if (file != null)
{
            // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(file);

            Guid encoderId = BitmapEncoder.JpegEncoderId;

            try
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await CaptureToStreamAsync(LayoutRoot, stream, encoderId);

                }
            }
            catch (Exception ex)
            {
                DisplayMessage(ex.Message);
            }
}
}

More details here.

like image 27
Fariha K Avatar answered Nov 15 '22 01:11

Fariha K