如何使用 swift 从核心图形 API 获取 window 列表

How to get window list from core-grapics API with swift

我正在尝试从 API 和 Swift 的核心图形 OSX 上获取 windows 的列表(以便稍后捕获它们的图像).经过一些研究,我发现 CGWindowListCopyWindowInfo Objective-C API 调用具有以下签名:

CFArrayRef CGWindowListCopyWindowInfo(
   CGWindowListOption option,
   CGWindowID relativeToWindow
);

Parameters

option: The options describing which window dictionaries to return. Typical options let you return dictionaries for all windows or for windows above or below the window specified in the relativeToWindow parameter. For more information, see Window List Option Constants.

relativeToWindow: The ID of the window to use as a reference point when determining which other window dictionaries to return. For options that do not require a reference window, this parameter can be kCGNullWindowID.

https://developer.apple.com/library/mac/documentation/Carbon/Reference/CGWindow_Reference/Reference/Functions.html

在我的 swift 应用程序中,我尝试这样使用它:

import Cocoa
import CoreFoundation

let option: CGWindowListOption = kCGWindowListOptionOnScreenOnly
let relativeToWindow: CGWindowID = kCGNullWindowID

let info = CGWindowListCopyWindowInfo(option, relativeToWindow)

但是XCode(游乐场)告诉我

我做错了什么?

  • kCGWindowListOptionOnScreenOnly是一个Int,你必须转换 CGWindowListOption 又名 UInt32.
  • C 定义

    #define kCGNullWindowID ((CGWindowID)0) 
    

    未导入到 Swift,因此您必须使用常量 0.

  • 另外,CGWindowListCopyWindowInfo()returns一个Unmanaged<CFArray>!,所以你要调用takeRetainedValue() 关于返回值(如 "Working with Cocoa Data Types" 中所述)。

在一起:

let option = CGWindowListOption(kCGWindowListOptionOnScreenOnly)
let relativeToWindow = CGWindowID(0)
let info = CGWindowListCopyWindowInfo(option, relativeToWindow).takeRetainedValue()

然后你可以用

枚举这个字典数组
for dict in info as! [ [ String : AnyObject] ] {
    // ...
}

Swift3 的更新:

if let info = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[ String : Any]] {
    for dict in info {
        // ...
    }
}