Skip to content

Instantly share code, notes, and snippets.

@steventheworker
Last active April 21, 2022 19:22
Show Gist options
  • Save steventheworker/6acd478c81c0b5c85ca1a18d3068305a to your computer and use it in GitHub Desktop.
Save steventheworker/6acd478c81c0b5c85ca1a18d3068305a to your computer and use it in GitHub Desktop.
reclaimFocus (by u/TheHiddenHeathen) v1.0 as seen on: r/MacOS/comments/u7egn7/window_management_lack_of_consistency_drives_me
// compile it with swiftc in terminal and then run output binary as shell script within BetterTouchTool.
import Cocoa
func reclaimFocus() {
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
guard
let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else {
return
}
if let window = infoList.first(where: { ($0["kCGWindowLayer"] as? Int32) == 0 }), let pid = window["kCGWindowOwnerPID"] as? Int32 {
let app = NSRunningApplication(processIdentifier: pid)
app?.activate(options: .activateIgnoringOtherApps)
} else {
let finder = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.finder")
finder[0].activate(options: .activateIgnoringOtherApps)
}
}
reclaimFocus()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment