加载My App时以编程方式截取屏幕截图

时间:2013-12-13 08:24:47

标签: c# xaml windows-phone-7 windows-phone-8

我正在尝试在加载My App时进行屏幕截图,没有任何用户交互。

我的代码就像这样

 public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(ApplicationBarIconButton);

    }

    private void ApplicationBarIconButton(object sender, EventArgs e)
    {
        var fileName = String.Format("WmDev_{0:}.jpg", DateTime.Now.Ticks);
        WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
        bmpCurrentScreenImage.Render(LayoutRoot, new MatrixTransform());
        bmpCurrentScreenImage.Invalidate();
        SaveToMediaLibrary(bmpCurrentScreenImage, fileName, 100);
        MessageBox.Show("Captured image " + fileName + " Saved Sucessfully", "WmDev Capture Screen", MessageBoxButton.OK);

        currentFileName = fileName;
    }

    public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality)
    {
        using (var stream = new MemoryStream())
        {
            // Save the picture to the Windows Phone media library.
            bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
            stream.Seek(0, SeekOrigin.Begin);
            new MediaLibrary().SavePicture(name, stream);
        }
    }

我收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:3)

诺基亚开发者维基上的这篇文章解释了如何捕获你的应用程序屏幕程序(你也可以找到一个广泛的代码示例):

http://developer.nokia.com/Community/Wiki/How_to_capture_screen_programmatically_in_Windows_Phone_7

没有API允许您从应用内部截取整个屏幕的屏幕截图(例如拍摄另一个应用)。

关于该错误,您在图片中向我们显示,您的应用似乎无权将图片保存在MediaLibrary中。

尝试将代码放在try-catch块内的方法SaveToMediaLibrary中:

    public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality)
{
    using (var stream = new MemoryStream())
    {
        try
        {
           // Save the picture to the Windows Phone media library.
           bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
           stream.Seek(0, SeekOrigin.Begin);
           new MediaLibrary().SavePicture(name, stream);
        }
        catch(UnauthorizedAccessException uae)
        {
          // log the exception message, uae.Message, in your favourite way :)
        }
    }
}

如果对SaveLibrary()的调用发生异常,如msdn上的this article所示,在第一个回答中,您需要在应用清单中指定媒体库功能,像这样:ID_CAP_MEDIALIB

我希望这会有所帮助。