Search code examples
swift3macos-sierra

How to get window id from the title by swift3


How can I get a CGWindowID from the title of it?

I thought I can get list of titles by this code

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

But it seems there is no info for title of the windows.

How can I get CGWindowID or any info to specify a window by title?


Solution

  • Actually the code snippet you posted seems to work for me. All I did was to iterate over the dictionary and find the window info for a given window title.

    Here is the code:

    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
    }
    

    With the above function, I am able to get a window's details, including name for example.

    I hope it works for you too.