Swift macOS, listen to open, close events of any application

I figure out the windows of external apps that the user has opened in a moment in time:

let options = CGWindowListOption(arrayLiteral: .excludeDesktopElements, .optionOnScreenOnly)
let windowsListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowsListInfo as ! [[String: Any ]]
let visibleWindows = infoList.filter{ $0["kCGWindowLayer"] as! Int == 0 }

But is there any way I can detect when the user closes one of those windows or opens a new one?

Can you explain more about your high-level goal here?

The reason I ask is that your question is very specific to macOS, and thus off-topic for Swift Forums. I’d like to give you a pointer to a better place to ask this, but it’s hard to do that without more context.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Thank you for your answer.

I want to know how many windows the user has from a specific program. I would like to have the information that we have in the dock when we click to an app. For instance, if we click TextEdit, we know each moment what windows we have from TextEdit.

With the code above I can know the situation in a point in time: when he launches the application or when he clicks a button. But, if the user closes or opens some window everything changes. I need to keep track of the situation.

I am quite new. I want to learn and I would appreciate any orientation.

Thank you!

Most tools that do this use the Accessibility API (in contrast to CGWindow, which is typically used by folks doing screen shots, remote access, and so on). The Accessibility API is callable from Swift, but there’s nothing Swift specific about it, so you’d be better off asking questions in a general Mac forum, like the App Frameworks > Cocoa topic area on DevForums.

A place to start would be the UIElementInspector sample code. It’s old, but the core concepts of the Accessibility API haven’t changed since then.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

Thank your very much for your answer.