如何从Swift的Core-Grapics API获取窗口列表 [英] How to get window list from core-grapics API with swift
问题描述
我正在尝试使用Swift从核心图形API中获取OSX上的窗口列表(以便稍后捕获它们的图像).经过一番研究,我发现了带有以下签名的CGWindowListCopyWindowInfo Objective-C API调用:
I´m trying to get a list of windows on OSX from the core-graphics API with Swift (to capture an image of them later on). After some research I found the CGWindowListCopyWindowInfo Objective-C API call with the following signature:
CFArrayRef CGWindowListCopyWindowInfo(
CGWindowListOption option,
CGWindowID relativeToWindow
);
参数
option:描述要哪些窗口词典的选项 返回.典型选项可让您返回所有窗口或 对于在指定窗口上方或下方的窗口 relativeToWindow参数.有关更多信息,请参见窗口列表. 选项常量.
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:用作窗口的ID 确定其他窗口词典要参考的参考点 返回.对于不需要参考窗口的选项,此 参数可以是kCGNullWindowID.
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.
在我的快速应用程序中,我试图像这样使用它:
In my swift application I tried to use it like this:
import Cocoa
import CoreFoundation
let option: CGWindowListOption = kCGWindowListOptionOnScreenOnly
let relativeToWindow: CGWindowID = kCGNullWindowID
let info = CGWindowListCopyWindowInfo(option, relativeToWindow)
但是XCode(操场)告诉我
But XCode (playground) tells me
- 它不能将int用作CGWindowListOption(kCGWindowListOptionOnScreenOnly == 0)
- kCGNullWindowID是一个无法解析的标识符
我在做什么错了?
推荐答案
-
kCGWindowListOptionOnScreenOnly
是Int
,您必须转换 到CGWindowListOption
又名UInt32
. -
C定义
kCGWindowListOptionOnScreenOnly
is anInt
, you have to convert that toCGWindowListOption
akaUInt32
.The C definition
#define kCGNullWindowID ((CGWindowID)0)
不会导入到Swift中,因此您必须使用常量
0
.is not imported into Swift, therefore you have to use the constant
0
.一起:
let option = CGWindowListOption(kCGWindowListOptionOnScreenOnly) let relativeToWindow = CGWindowID(0) let info = CGWindowListCopyWindowInfo(option, relativeToWindow).takeRetainedValue()
然后,您可以使用以下方法枚举该字典数组
Then you can enumerate this array of dictionaries with
for dict in info as! [ [ String : AnyObject] ] { // ... }
更新迅速3:
if let info = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[ String : Any]] { for dict in info { // ... } }
这篇关于如何从Swift的Core-Grapics API获取窗口列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!