CGWindowListCreateImage doesn't *always* return the correct image

Doing a

guard let cgImage = CGWindowListCreateImage(.null, [.optionIncludingWindow], cgID, [.nominalResolution]) else { print ("problem!"); continue }

where cgID is a CGWindowID for a Desktop background image almost always returns an CGImage of the Desktop (minus any icons on the Desktop, of course).

However, under Monterey, there is a finite possibility of the returned image to be simply gray or some chopped up version of the actual Desktop. This usually happens when Spaces are changed and code is triggered to update the image from a NSWorkspace.shared.notificationCenter notification named: NSWorkspace.activeSpaceDidChangeNotification.

Is there a way to detect when the image returned is not correct? The else in the guard is never triggered and the cgImage is the correct size, just the wrong content. In fact comparing a good cgImage to a bad cgImage, there doesn't appear to be any difference.

Documentation for .optionIncludingWindow says

You must combine this option with the optionOnScreenAboveWindow or optionOnScreenBelowWindow option to retrieve meaningful results.

However, including either option (e.g. [.optionOnScreenBelowWindow, .optionIncludingWindow]) can still result in an incorrect image.

As an aside, https://developer.apple.com/videos/play/wwdc2019/701/ at the 15:49 mark shows using only the optionIncludingWindow, so not sure which documentation is correct.

One clue is when the code starts, it always captures the Desktop background images correctly. It seems to fail only when the NSWorkspace.activeSpaceDidChangeNotification is sent. Introducing a block for 0.25 seconds seems to insure the image capture succeeds.

Would prefer a better option than blocking.

This sounds like a bug/regression to me. Would you be able to create a repro case and file a bug report on Feedback assistant? If you do, post the feedback ID here and I can route it to the CoreGraphics team for review.

Thanks for your response. https://feedbackassistant.apple.com/feedback/9824294

By definition the bug only occurs occasionally. Gave a link to the code and the line to comment out to get the problem to appear. Unfortunately, there is no deterministic way to reproduce.

CGWindowListCreateImage doesn't *always* return the correct image
 
 
Q