Thursday, March 20, 2014

How to take a screenshot from Windows Phone application code

  1. Catch camera button press by subscribing to CameraButtons.ShutterKeyReleased event.
  2. Get current page from Application.RootVisual property.
  3. Create an instance of WriteableBitmap class using this page.
  4. Save it to MemoryStream using WriteableBitmap.SaveJpeg extension method.
  5. Save image to JPEG file in public "Pictures/Saved Pictures" folder using MediaLibrary.SavePicture method.
Full code example below.

namespace Screenshot
{
    using System;
    using System.IO;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using Microsoft.Devices;
    using Microsoft.Phone.Controls;
    using Microsoft.Xna.Framework.Media;

    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            CameraButtons.ShutterKeyReleased += OnCameraButtonsShutterKeyReleased;
        }

        private void OnCameraButtonsShutterKeyReleased(Object sender, EventArgs e)
        {
            try
            {
                String fileName = "screenshot_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".jpg";

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(Application.Current.RootVisual, null);
                    writeableBitmap.SaveJpeg(memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);

                    memoryStream.Position = 0;

                    using (MediaLibrary mediaLibrary = new MediaLibrary())
                    {
                        mediaLibrary.SavePicture(fileName, memoryStream);
                    }
                }

                MessageBox.Show("Screenshot saved to " + fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error saving screenshot: " + ex.Message);
            }
        }
    }
}

No comments:

Post a Comment