In a Windows 8 app (C#) using the MediaCapture class (Windows.Media.Capture) to show a webcam feed, I’m trying to restart the preview when the app has lost and then come back into focus (e.g. by clicking in the top left screen corner to another app, then clicking again to come back to my app).
How I’m trying to restart the preview right now is:
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, the Resuming and Suspending events don’t seem to fire in the example I describe above. Is this not “suspending” an app? If so, what is it/what events should I be on the lookout for?
Alternatively, should I, instead of using a long-running “preview” to display the webcam, use one of the this.stream.StartRecord... methods?
EDIT: If I fire the events manually using Visual Studio’s Suspend/Resume button (on the Debug Location toolbar), the functionality works as desired (the video restarts when the app is resumed).
I see a few things wrong:
async void; useasync Taskfor all methods except event handlers.Suspending, use the deferral provided byargs.SuspendingOperation.GetDeferralif you have anasyncevent handler.