Skip to content

Instantly share code, notes, and snippets.

@c9iim
Last active May 9, 2023 07:45
Show Gist options
  • Save c9iim/4e27150198b7a8703794 to your computer and use it in GitHub Desktop.
Save c9iim/4e27150198b7a8703794 to your computer and use it in GitHub Desktop.
AXUIElement in Swift
import Cocoa
protocol AXUIProtocol {
func AXUIWindowArray(processIdentifier pid:pid_t) -> [AXUIElement]
func AXUIWindowArray(bundleIdentifier bid:NSString) -> [AXUIElement]
}
extension AXUIProtocol {
func AXUIWindowArray(processIdentifier pid:pid_t) -> [AXUIElement] {
let windowList : UnsafeMutablePointer<AnyObject?> = UnsafeMutablePointer<AnyObject?>.alloc(1)
let appRef = AXUIElementCreateApplication(pid).takeRetainedValue()
AXUIElementCopyAttributeValue(appRef, "AXWindows", windowList)
return windowList.memory as! [AXUIElement]
}
func AXUIWindowArray(bundleIdentifier bid:NSString) -> [AXUIElement] {
let runningApplications = NSWorkspace.sharedWorkspace().runningApplications
if let application = runningApplications.filter({$0.bundleIdentifier == bid}).first {
return AXUIWindowArray(processIdentifier: application.processIdentifier)
} else {
return []
}
}
}
class ApplicationDelegate: NSObject, NSApplicationDelegate, AXUIProtocol {
func applicationDidFinishLaunching(aNotification: NSNotification) {
var windows : [AXUIElement]?
// Get Active Applilcation
if let application = NSWorkspace.sharedWorkspace().frontmostApplication {
let localizedName = application.localizedName
let processIdentifier = application.processIdentifier
NSLog("localizedName: \(localizedName), processIdentifier: \(processIdentifier)")
windows = AXUIWindowArray(processIdentifier: processIdentifier)
NSLog("windows: \(windows)")
if let bundleIdentifier = application.bundleIdentifier {
NSLog("bundleIdentifier: \(bundleIdentifier)")
windows = AXUIWindowArray(bundleIdentifier: bundleIdentifier)
NSLog("windows: \(windows)")
}
}
// Get Applilcation by bundleIdentifier
windows = AXUIWindowArray(bundleIdentifier: "com.apple.finder")
NSLog("windows: \(windows)")
//
NSRunningApplication.currentApplication().terminate()
}
}
let applicationDelegate = ApplicationDelegate()
let application = NSApplication.sharedApplication()
application.setActivationPolicy(NSApplicationActivationPolicy.Accessory)
application.delegate = applicationDelegate
application.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment