Vaibhav
Vaibhav

Reputation: 359

Starting camera on resume in windows store app

We are developing normal bar code scanner app for windows surface tablets. In onNavigatedTo method of page we are invoking camera..

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(); 

It is working fine.

Now App goes to background and comes back to foreground. But we are unable to invoke camera again on resume using same code

 await App.camera.StartPreviewAsync(); 

How to do it?

Upvotes: 1

Views: 226

Answers (1)

Abdallah Shakhatreh
Abdallah Shakhatreh

Reputation: 770

You need to use events such as Activated and VisibilityChanged :

private MediaCapture m_mediaCaptureMgr;

public MainPage()
{
    this.InitializeComponent();

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

}

And then Initialize and StartPreview your camera on 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();
    }
}

And Stop Camera on Current_VisibilityChanged :

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

Upvotes: 2

Related Questions