Skip to content

CameraView: Fixed crash on Windows when app has no camera access anymore - #3299

Open
MFinkBK wants to merge 2 commits into
CommunityToolkit:mainfrom
MFinkBK:windows-cameraview-fix-UnauthorizedAccessException
Open

MFinkBK wants to merge 2 commits into
CommunityToolkit:mainfrom
MFinkBK:windows-cameraview-fix-UnauthorizedAccessException

Conversation

@MFinkBK

@MFinkBK MFinkBK commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Description of Change

The change handles the UnauthorizedAccessException in InitializeCameraForCameraView and the loop in PlatformRefreshAvailableCameras() is just continue'd.

Linked Issues

PR Checklist

  • Has a linked Issue, and the Issue has been approved(bug) or Championed (feature/proposal)
  • Has tests (if omitted, state reason in description)
  • Has samples (if omitted, state reason in description)
  • Rebased on top of main at time of PR
  • Changes adhere to coding standard
  • Documentation created or updated: https://github.com/MicrosoftDocs/CommunityToolkit/pulls

Additional information

I'm not sure if catching the exception and just returning a bool is OK here, or if the PlatformRefreshAvailableCameras() should catch the exceptions instead.

There's still an uncatchable CameraException in the ConnectCamera() handler, which should probably also be handled differently.

Comment thread src/CommunityToolkit.Maui.Camera/Extensions/CameraViewExtensions.windows.cs Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to prevent Windows apps from crashing when CameraView is used after camera permission has been revoked, by treating UnauthorizedAccessException during MediaCapture initialization as a recoverable failure instead of an unhandled exception.

Changes:

  • Updated InitializeCameraForCameraView (Windows) to return a bool indicating initialization success and to catch UnauthorizedAccessException.
  • Updated Windows camera enumeration (PlatformRefreshAvailableCameras) to skip devices whose initialization fails.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/CommunityToolkit.Maui.Camera/Providers/CameraProvider.windows.cs Skips camera devices that fail MediaCapture initialization during available-camera refresh.
src/CommunityToolkit.Maui.Camera/Extensions/CameraViewExtensions.windows.cs Returns a success flag from initialization and handles UnauthorizedAccessException without throwing.
Suppressed comments (1)

src/CommunityToolkit.Maui.Camera/Extensions/CameraViewExtensions.windows.cs:52

  • The COMException catch says "Camera already initialized" (which was previously treated as non-fatal), but the new bool return reports this as failure. That changes behavior for callers like PlatformRefreshAvailableCameras(), which will now drop/skip that device entirely. If COMException here really means "already initialized", this should be reported as success.
		catch (System.Runtime.InteropServices.COMException)
		{
			// Camera already initialized
			return false;
		}

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/CommunityToolkit.Maui.Camera/Providers/CameraProvider.windows.cs Outdated
Comment thread src/CommunityToolkit.Maui.Camera/Extensions/CameraViewExtensions.windows.cs Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

src/CommunityToolkit.Maui.Camera/Providers/CameraProvider.windows.cs:28

  • When camera initialization fails (e.g., access revoked), this continue skips adding any entry to availableCameras. That can leave AvailableCameras empty even though a camera device exists, and CameraManager.PlatformStartCameraPreview will still throw CameraException("No camera available on device"), which is typically unhandled from the handler path (still an app crash). Consider still adding a CameraInfo entry with conservative defaults when initialization is denied so the camera list isn’t empty, and let preview-start handle the access failure without throwing.
			bool success = await mediaCapture.InitializeCameraForCameraView(sourceGroup.Id, token);

			if (!success)
			{
				continue;
			}

Comment thread src/CommunityToolkit.Maui.Camera/CameraManager.windows.cs Outdated
@MFinkBK

MFinkBK commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

@bijington @TheCodeTraveler How can we proceed with this bugfix? I'm happy to apply any suggestions you make to my PR. Thanks!

@MFinkBK
MFinkBK force-pushed the windows-cameraview-fix-UnauthorizedAccessException branch from 48c6c07 to b41c069 Compare September 10, 2026 14:23
@MFinkBK

MFinkBK commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

I rebased the PR on top of latest main branch, reverted the change to InitializeCameraForCameraView() and handled the exceptions instead. Also removed throwing exceptions in CameraManager.ConnectCamera(). This would fix the crash, but the user would get no diagnostics. Still open to discussion on how to handle that.

@MFinkBK

MFinkBK commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

It seems all the builds fail because this unrelated error:

error NU1902: Warning As Error: Package 'Microsoft.Build.Tasks.Git' 8.0.0 has a known moderate severity vulnerability

I can't see where the package is referenced in the project, though.

@MFinkBK

MFinkBK commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@TheCodeTraveler @bijington @jfversluis Unfortunately I didn't hear back from you. How can we proceed with this PR and the original bug? I'm open for discussion. Thank you!

@jfversluis

Copy link
Copy Markdown
Member

I think the error you were seeing was from some dependency in another project/the pipeline. I just updated this PR with all the latest changes on main. Let's see if that fixes it for you!

@MFinkBK

MFinkBK commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

There is one open question for this PR, though, and it's what should be discussed.

The original app crash occured because CameraManager.ConnectCamera() threw an exception, and CameraView.ConnectHandler(), which calls it, is called by .NET MAUI to set up the handler for CameraView. .NET MAUI does no exception handling there, so the app crashed.

My PR now fixes the app crash by catching all exceptions in CameraManager.ConnectCamera(), but the user gets no diagnostic, just an empty list in AvailableCameras and a null SelectedCamera.

There are some possibilities:

  1. Just catch the exceptions, leave AvailableCameras empty. This PR does this.
  2. Have a diagnostics Action<string> or Func<Task, string> or something that reports this.
  3. Do it like the Xamarin.CommunityToolkit: Raise the MediaCapturedFailed, but this may be unintuitive, since there's no capture in progress
  4. Raise a new event, something like CameraConnectFailed or something named more generic.
  5. Do something entirely different.

@bijington

Copy link
Copy Markdown
Contributor

Sorry I missed earlier notifications.

I think we should just add an event for all camera related errors for now and pump caught exceptions through it. Then it is at least consistent with the MediaElement to some extent. Maybe something like ErrorOccurred or ExceptionCaught?

…nymore

don't throw exceptions in CameraManager.ConnectCamera(), since no one can handle them and they just crash the whole app
@MFinkBK
MFinkBK force-pushed the windows-cameraview-fix-UnauthorizedAccessException branch from fef18c3 to 3a89bc6 Compare October 7, 2026 13:07
@MFinkBK

MFinkBK commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

I just rebased my PR branch on top of main and rearranged the commits. The first one adds the ErrorOccurred event to CameraView, and the second one fixes the crash on Windows, when connecting the handler and when trying to start the preview. That fixes the app crash on Windows and reports the exception through the event instead.

Feel free to review. Thank you!

@bijington bijington left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me! Thanks for this @MFinkBK

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +155 to +160
catch (Exception ex)
{
// can't use that camera
cameraView.OnErrorOccurred(ex);
return;
}
Comment on lines +28 to +32
catch (Exception)
{
// can't use that camera
continue;
}

cameraView.SelectedCamera ??= cameraProvider.AvailableCameras?.FirstOrDefault();

if (cameraView.SelectedCamera == null)
cameraView.SelectedCamera ??= cameraProvider.AvailableCameras?.FirstOrDefault() ?? throw new CameraException("No camera available on device");
cameraView.SelectedCamera ??= cameraProvider.AvailableCameras?.FirstOrDefault();

if (cameraView.SelectedCamera == null)
/// <summary>
/// Event args containing all contextual information related to the error occurred event.
/// </summary>
/// <param name="ex">The <see cref="Exception"/>exception.</param>
}

/// <summary>
/// Event that is raised when the an error occurred.
Comment on lines +319 to +321
void ICameraView.OnErrorOccurred(Exception ex)
{
weakEventManager.HandleEvent(this, new ErrorOccurredEventArgs(ex), nameof(ErrorOccurred));
@TheCodeTraveler

Copy link
Copy Markdown
Collaborator

@MFinkBK Could you please address CoPilot's comments before we merge?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] CameraView on Windows crashes the app when permission is removed

5 participants