如何將這段AppleScript代碼翻譯成Swift?
告訴應用程式 "System Events" to告訴行程 "Safari" to get UI elements of first window
我已經到達了 "Safari "的第一個視窗,但我不知道如何獲得UI元素
。let pid = NSWorkspace.share.runningApplications.first(where: {$0.localizedName == "Safari"})?.processIdentifier
let appRef = AXUIElementCreateApplication(pid!)
var windows。AnyObject?
_ = AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, & windows)
if let firstWindow =(windows as? [AXUIElement])? .first{
print(firstWindow)
}
uj5u.com熱心網友回復:
你可以使用同樣的AXUIElementCopyAttributeValue()來查詢視窗的孩子,以及孩子的孩子,等等。
在可能的情況下,我自己喜歡在現有的型別上添加擴展,以獲得更好的清晰度:
我喜歡在現有的型別上添加擴展。
extension AXUIElement {
var children: [AXUIElement]? {
var childrenPtr: CFTypeRef?
AXUIElementCopyAttributeValue(appRef, kAXChildrenAttribute as CFString, &/span>childrenPtr)
return childrenPtr as? [AXUIElement]
}
}
然后你可以在你的代碼中使用它:
if let firstWindow = (windows as? [AXUIElement])? .first{
print(firstWindow, firstWindow.children)
}
你可以更進一步,通過向擴展添加更多的功能來簡化AXUIElement消費者代碼:
extension AXUIElement {
static func from(pid: pid_t) -> AXUIElement { AXUIElementCreateApplication(pid) }
var windows: [AXUIElement]? { value(forAttribute: kAXWindowsAttribute) }
var children: [AXUIElement]? { value(forAttribute: kAXChildrenAttribute) }
func value<T>(forAttribute attribute。String) -> T? {
var attributeValue。CFTypeRef?
AXUIElementCopyAttributeValue(self, attribute as CFString, & /span>attributeValue)
return attributeValue as? T。
}
}
let pid = ..._/span>
let app = AXUIElement.from(pid: pid! )
if let firstWindow = app.windows? /span>.first{
print(firstWindow, firstWindow.children)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/320039.html
標籤:
上一篇:如何處理C 中的值多載例外?
下一篇:繼承性應該對靜態變數起作用
