如何通过swift3从标题中获取窗口ID

时间:2017-11-07 20:16:14

标签: swift3 macos-sierra

如何从标题中获得CGWindowID

我以为我可以通过此代码获得标题列表

let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]

https://stackoverflow.com/a/31367468/1536527

但似乎没有关于Windows标题的信息。

如何获取CGWindowID或任何信息以按标题指定窗口?

1 个答案:

答案 0 :(得分:2)

实际上,您发布的代码段似乎对我有用。我所做的只是迭代字典并找到给定窗口标题的窗口信息。

以下是代码:

func getWindowInfo(pname: String) -> Dictionary<String, AnyObject> {
    var answer = Dictionary<String, AnyObject>()
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]


    infoList?.forEach{eachDict in
        eachDict.keys.forEach{ eachKey in
            if (eachKey == "kCGWindowName" && eachDict[eachKey] != nil ){
                let name = eachDict[eachKey] as? String ?? ""
                print (name)
                if ( name == pname){
                    print("******** Found **********")
                    answer = eachDict as! Dictionary<String, AnyObject>
                }
            }
            print(eachKey , "-->" , eachDict[eachKey])
        }
    }
    return answer
}

通过上述功能,我可以获得窗口的详细信息,例如名称。

我希望它也适合你。