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
optionOnScreenAboveWindoworoptionOnScreenBelowWindowoption 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.