How to set the desktop image to NSWindow Background image in mac os application programatically. Suppose if I click a button then whatever the desktop image is there it should apply to NSWindow Background.
-
1Possible duplicate of [Cocoa: take screenshot of desktop wallpaper (without icons and windows)](https://stackoverflow.com/questions/8082837/cocoa-take-screenshot-of-desktop-wallpaper-without-icons-and-windows) – ekscrypto Aug 16 '18 at 14:41
-
https://stackoverflow.com/a/32918072/1889814 – StefanS Aug 16 '18 at 18:29
2 Answers
To obtain a screen's desktop image you use methods provided by NSWorkspace
.
The method desktopImageURLForScreen:
returns a URL for the image file, while the method desktopImageOptionsForScreen:
returns a dictionary of desktop image options - how images should be scaled, whether they should be tiled, etc.
Using those methods and an NSImageView
you should be able to display the desktop image appropriately scaled, tiled and aligned as a window background. If you are supporting windows spanning screens on multi-screen systems it will be a bit more involved but the method is essentially the same.
HTH

- 52,522
- 5
- 70
- 86
CRD suggestion does work if the app is not Sandboxed. If it is, then you can't do anything with NSWorkspace.shared.desktopImageURL(for: screen)
.
you can play with Core Graphics and grab a picture of the Desktop(s):
extension NSImage {
static func desktopPictures() -> [NSImage] {
let info = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[ String : Any]]
var images = [NSImage]()
for window in info! {
// we need windows owned by Dock
let owner = window["kCGWindowOwnerName"] as! String
if owner != "Dock" {
continue
}
// we need windows named like "Desktop Picture %"
let name = window["kCGWindowName"] as! String
if !name.hasPrefix("Desktop Picture") {
continue
}
// this belongs to a screen
let index = window["kCGWindowNumber"] as! CGWindowID
let cgImage = CGWindowListCreateImage(CGRect.infinite, CGWindowListOption(arrayLiteral: CGWindowListOption.optionIncludingWindow), index, CGWindowImageOption.nominalResolution)
images.append(NSImage(cgImage: cgImage!, size: NSMakeSize(CGFloat(cgImage!.width), CGFloat(cgImage!.height))))
}
// return the array of Desktop images
return images
}
}
and then to get Desktop images
NSImage.desktopPictures()
thanks to Cocoa: take screenshot of desktop wallpaper (without icons and windows) and How to get window list from core-grapics API with swift

- 141
- 1
- 4