How to get window id from header by swift3

How can I get CGWindowIDfrom its name?

I thought I could get a list of names for this code.

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

stack overflow

But there seems to be no information for the name of the windows.

How can I get CGWindowIDor any information to indicate a window by name?

+4
source share
1 answer

Actually the code snippet you posted works for me. All I did was iterate over the dictionary and find the window information for the 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
}

Using the specified function, I can get information about the window, including the name, for example.

I hope this works for you too.

+2
source

Source: https://habr.com/ru/post/1688906/


All Articles