Skip to content

Instantly share code, notes, and snippets.

@Hexfire
Forked from c9iim/AXUIElement_in_Swift.swift
Created November 7, 2017 12:13
Show Gist options
  • Save Hexfire/221d31b0477009052af895680cf0466c to your computer and use it in GitHub Desktop.
Save Hexfire/221d31b0477009052af895680cf0466c 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