在Windows商店应用程序中恢复启动相机

时间:2014-12-09 11:53:22

标签: c#-4.0 windows-store-apps windows-8.1

我们正在开发用于Windows平板电脑的普通条形码扫描仪应用程序。在onNavigatedTo页面方法中,我们正在调用相机..

var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
        await App.camera.InitializeAsync(new MediaCaptureInitializationSettings
        {
            VideoDeviceId = devices[1].Id
        });

        cap.Source = App.camera;
        cap.Visibility = Visibility.Visible;
        await App.camera.StartPreviewAsync(); 

工作正常。

现在App转到后台并回到前台。但是我们无法调用相机 再次使用相同的代码恢复

 await App.camera.StartPreviewAsync(); 

怎么做?

1 个答案:

答案 0 :(得分:2)

您需要使用ActivatedVisibilityChanged等事件:

private MediaCapture m_mediaCaptureMgr;

public MainPage()
{
    this.InitializeComponent();

    Window.Current.Activated+=Current_Activated;
    Window.Current.VisibilityChanged+=  Current_VisibilityChanged;

}

然后InitializeStartPreview您的相机 Current_Activated

private async void Current_Activated(object sender, WindowActivatedEventArgs e)
{
    try
    {
        m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
        await m_mediaCaptureMgr.InitializeAsync();
        cap.Source = m_mediaCaptureMgr;
        await m_mediaCaptureMgr.StartPreviewAsync();

    }
    catch (Exception exception)
    {
       new MessageDialog("Unable to start the video capture.").ShowAsync();
    }
}

Stop相机 Current_VisibilityChanged

private async void Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
    try
    {
        await m_mediaCaptureMgr.StopPreviewAsync();
    }
    catch (Exception exception)
    {
    }
}