简体   繁体   中英

How to set desktop image to NSWindow programmatically objective c?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM