Cocoa: take screenshot of desktop wallpaper (without icons and windows)

后端 未结 3 1114
北荒
北荒 2020-12-17 05:13

Is is possible to capture the Mac OS X desktop without desktop items and any windows that may be open (i.e. just the wallpaper)?

I\'ve experimented with CGWind

3条回答
  •  余生分开走
    2020-12-17 05:38

    Swift version:

    extension NSImage {
    
        static func desktopPicture() -> NSImage {
    
            let windows = CGWindowListCopyWindowInfo(
                CGWindowListOption.OptionOnScreenOnly,
                CGWindowID(0))! as NSArray
    
            var index = 0
            for var i = 0; i < windows.count; i++  {
                let window = windows[i]
    
                // 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
                }
    
                // wee need the one which belongs to the current screen
                let bounds = window["kCGWindowBounds"] as! NSDictionary
                let x = bounds["X"] as! CGFloat
                if x == NSScreen.mainScreen()!.frame.origin.x {
                    index = window["kCGWindowNumber"] as! Int
                    break
                }
            }
    
            let cgImage = CGWindowListCreateImage(
                CGRectZero,
                CGWindowListOption(arrayLiteral: CGWindowListOption.OptionIncludingWindow),
                CGWindowID(index),
                CGWindowImageOption.Default)!
    
            let image = NSImage(CGImage: cgImage, size: NSScreen.mainScreen()!.frame.size)
            return image
        }
    }
    

提交回复
热议问题