Restart MediaCapture when the application returns to focus

In a Windows 8 (C #) app, using the class MediaCapture

( Windows.Media.Capture

) to show the webcam feed, I try to restart the preview when the app is lost and then return to focus (for example, by clicking in the upper left corner of the screen to another app while then clicking again to return to my app).

How do I try to restart the preview right now:

Application.Current.Resuming += (sender, o) => StartVideo(video);
Application.Current.Suspending += (sender, args) => StopVideo();

internal async void StartVideo(CaptureElement e)
{
    try
    {
        this.stream = new MediaCapture();
        await this.stream.InitializeAsync();
        e.Source = this.stream;
        await this.stream.StartPreviewAsync();
    }
    catch
    {
        new MessageDialog("Unable to start the video capture.").ShowAsync();
    }
}

internal async void StopVideo()
{
    try
    {
        await stream.StopPreviewAsync();
    }
    catch { }
}

      

But events Resuming

and Suspending

don't seem to fire in the example above. Doesn't that "pause" the application? If so, what is it / what events should I be looking for?

Alternatively, should I, instead of using a long "preview" to display the webcam, use one of the methods this.stream.StartRecord...

?

EDIT: If I trigger events manually using the Visual Studio Pause / Resume button (in the Debug toolbar), the functionality works as desired (the video resumes when the app is resumed).

+3


source to share


1 answer


I see several errors:



  • You should avoid async void

    ; use async Task

    for all methods except event handlers.
  • For "command" events such as Suspending

    , use the deferral provided args.SuspendingOperation.GetDeferral

    if you have an event handler async

    .
+1


source







All Articles