How can I get a list of all windows, currently on the screen, in swift? (all examples are preceded by import Cocoa
)
我如何能得到一个所有窗口的列表,目前在屏幕上,以swift?(所有示例前面都有import Cocoa)
In objective-c I can run the following code successfully:
在objective-c中,我可以成功运行以下代码:
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
But when I run the equivalent in swift(using the playground to test):
但是当我在swift跑的时候(用操场测试):
let windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kcGNullWindowID)
I get an error telling me that I have an Use of unresolved identifier 'kcGNullWindowID'
.
我得到一个错误,告诉我使用了未解析标识符'kcGNullWindowID'。
After playing around with the help of the quartz documentation for a while I have gotten to:
在quartz文档的帮助下玩了一段时间之后,我发现:
let windowList = CGWindowListCopyWindowInfo(CGWindowListOption(kCGWindowListOptionOnScreenOnly), CGWindowListOption(0))
But it still does not work as I am receiving a {__NSArrayM}
object, which I do not know how to access.
但是它仍然不能工作,因为我正在接收一个{__NSArrayM}对象,我不知道如何访问它。
Am I on the right track or am I doing something fundamentally wrong?
我是走在正确的道路上,还是做了一些根本错误的事情?
19
Here's an example in Swift 2.0, which also demonstrates multiple options.
下面是Swift 2.0中的一个示例,它还演示了多种选项。
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.ExcludeDesktopElements, CGWindowListOption.OptionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]
6
Use takeUnretainedValue()
or takeRetainedValue()
on windowList
.
在窗口列表中使用takeUnretainedValue()或takeRetainedValue()。
Check out Apple's Using Swift with Cocoa and Objective-C and read the section called Working with Cocoa Data Types and look for Unmanaged Objects.
查看一下Apple在Cocoa和Objective-C中使用Swift,并阅读“使用Cocoa数据类型”一节,并查找非托管对象。
Here is a concrete example:
这里有一个具体的例子:
import Cocoa
let windowInfosRef = CGWindowListCopyWindowInfo(CGWindowListOption(kCGWindowListOptionOnScreenOnly), CGWindowID(0))
let windowInfos = windowInfosRef.takeRetainedValue().__conversion() // cast to swift dictionary
println(windowInfos) // print the swift dictionary
1
Here's my version for Swift 1.2. It's more explicit about types, since we know the function returns an array of dictionaries with string keys.
这是我的版本。它对类型更明确,因为我们知道函数返回一个带有字符串键的字典数组。
let options = CGWindowListOption(kCGWindowListOptionOnScreenOnly)
let cfInfoList = CGWindowListCopyWindowInfo(options, CGWindowID(0)).takeRetainedValue()
let infoList = cfInfoList as NSArray as? [[String: AnyObject]]
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2014/06/07/86a00c666099cb5b6f8da9a6cd1e462.html。