private async void TakePictureButton_Click(object sender, RoutedEventArgs e) { MediaCapture capture = null; try { capture = new MediaCapture(); await capture.InitializeAsync(); } catch (TypeLoadException ex) { Log.WriteLine(ex.Message); } if (capture != null) { var preview = new PreviewImage(capture); this.Picture.Source = preview; await preview.StartAsync(); var outputFile = Utilities.AccountPictureFilePath(); TakePicture(capture, preview, outputFile, 3); } }
private async void TakePicture(MediaCapture capture, PreviewImage preview, string outputFile, int delay) { if (!File.Exists(outputFile)) { File.Create(outputFile).Close(); } StorageFile file = await StorageFile.GetFileFromPathAsync(outputFile); ImageEncodingProperties imgFormat = ImageEncodingProperties.CreatePng(); new Thread(delegate() { Thread.CurrentThread.IsBackground = true; Stopwatch stopwatch = Stopwatch.StartNew(); long millisecondsToWait = delay * 1000; int i = delay; while (true) { long now = stopwatch.ElapsedMilliseconds; if (now >= millisecondsToWait) { // take photo in async IAsyncAction action = capture.CapturePhotoToStorageFileAsync(imgFormat, file); while (true) { if (action.Status == AsyncStatus.Completed || action.Status == AsyncStatus.Error) { break; } Thread.Sleep(1); } Dispatcher.Invoke(new Action(() => { this.CountDown.Visibility = Visibility.Hidden; Task _ = preview.StopAsync(); capture.Dispose(); if (action.Status == AsyncStatus.Completed) { this.PictureFile = file.Path; } else { DeletePicture(); } LoadPicture(); ResetMessage(); ValidateField(this.Picture); })); break; } Dispatcher.Invoke(new Action(() => { this.CountDown.Visibility = Visibility.Visible; this.CountDown.Text = i.ToString(); })); i--; Thread.Sleep(1000); } }).Start(); }