I am trying to write a basic camera app using the auto-focus feature to process a barcode. If I press back just as the camera has focused, it goes to a blank screen and just hangs there – no exception is thrown. I have traced the problem to the CaptureImage() method, I can see it being called, but the OnCaptureImageAvailable method is never invoked. This happens even when I do not unhook the OnCaptureImageAvailable in the OnNavigatedFrom method.
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
_camera.AutoFocusCompleted -= OnCameraAutoFocusCompleted;
_camera.CaptureImageAvailable -= OnCaptureImageAvailable;
_camera.Initialized -= OnCameraInitialized;
_camera.Dispose();
_camera = null;
}
private void InitializeCamera()
{
_camera = new PhotoCamera();
_camera.Initialized += OnCameraInitialized;
viewfinderBrush.SetSource(_camera);
}
void OnCameraInitialized(object sender, EventArgs e)
{
_camera.Initialized -= OnCameraInitialized;
_camera.AutoFocusCompleted += OnCameraAutoFocusCompleted;
_camera.CaptureImageAvailable += OnCaptureImageAvailable;
_camera.FlashMode = FlashMode.Off;
_camera.Focus();
}
private void OnCameraAutoFocusCompleted(object sender, EventArgs e)
{
_camera.CaptureImage();
}
private void OnCaptureImageAvailable(object sender, ContentReadyEventArgs e)
{
if (_camera != null && e.ImageStream != null)
ScanBarcode(e);
}
The issue is you are going to the previous page and disposing the camera while the camera is busy capturing the image in “_camera.CaptureImage();”.
How about keeping two boolean flags: “doBack” and “captureCompleted”.
Then, do not go back when the OnCameraAutoFocusCompleted event triggers:
When the back key is pressed set the doBack flag and ignore, unless captureCompleted is set:
Then, when the OnCameraCaptureCompleted event triggers, set the captureCompleted flag en go to the previous page (and dispose the camera) if the doBack flag is set: