How to ignore my app's window on screenshot? (Swift 2.0)

喜夏-厌秋 提交于 2021-02-17 04:49:22

问题


I wanted to get an image of the screen, ignoring my app's window.

Found a code example in Objective-C and tried to convert it to Swift.

Objective-C snipped:

// Get onscreen windows
CGWindowID windowIDToExcude = (CGWindowID)[myNSWindow windowNumber];
CFArrayRef onScreenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
CFMutableArrayRef finalList = CFArrayCreateMutableCopy(NULL, 0, onScreenWindows);
for (long i = CFArrayGetCount(finalList) - 1; i >= 0; i--) {
    CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(finalList, i);
    if (window == windowIDToExcude)
            CFArrayRemoveValueAtIndex(finalList, i);
}
// Get the composite image
CGImageRef ref = CGWindowListCreateImageFromArray(myRectToGrab, finalList, kCGWindowListOptionAll);

My version in Swift (where I managed to get so far):

// Get onscreen windows
let windowIDToExcude = myNSWindow.windowNumber!
let onScreenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID)
let finalList = CFArrayCreateMutableCopy(nil, 0, onScreenWindows)

for var i = CFArrayGetCount(finalList) - 1; i >= 0; i-=1 {
    var window: CGWindowID = (uintptr_t(CFArrayGetValueAtIndex(finalList, i)) as! CGWindowID)
    if window == windowIDToExcude {
        CFArrayRemoveValueAtIndex(finalList, i)
    }
}
// Get the composite image
var ref = CGWindowListCreateImageFromArray(myRectToGrab, finalList, kCGWindowListOptionAll)

But it does not work in swift 2.0 and I have no idea why.

Particularly this line can't be compiled:

CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID)

Apparently there is no such thing as CGWindowListCreate, kCGWindowListOptionOnScreenOnly and kCGNullWindowID anymore.


回答1:


Can you try this:

let imageRef = CGWindowListCreateImage(self.view.frame, CGWindowListOption.OptionOnScreenBelowWindow, CGWindowID(self.view.window!.windowNumber), CGWindowImageOption.Default)

let image = NSImage(CGImage: imageRef!, size: self.view.frame.size)
self.imageView.image = image

That does the trick for me.



来源:https://stackoverflow.com/questions/37043708/how-to-ignore-my-apps-window-on-screenshot-swift-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!