我想递归地查询Books.app的子元素,以获取所有可单击的元素。
但是,我注意到似乎无法从Books窗口元素中获取AXChildren
属性的值。
您可以在游乐场中试用的代码片段:
import Cocoa
guard let books = NSWorkspace.shared.runningApplications.first(where: { $0.bundleIdentifier == "com.apple.iBooksX" }) else {
fatalError()
}
let booksPid = books.processIdentifier
let booksElement = AXUIElementCreateApplication(booksPid)
var bookRole: AnyObject?
let bookRoleError = AXUIElementCopyAttributeValue(booksElement, "AXRole" as CFString, &bookRole)
print("query book role error: \(bookRoleError.rawValue)")
print("book role: \(bookRole)")
var bookFocusedWindow: AnyObject?
let bookFocusedWindowError = AXUIElementCopyAttributeValue(booksElement, "AXFocusedWindow" as CFString, &bookFocusedWindow)
print("book focused window error: \(bookFocusedWindowError.rawValue)")
print("book focused window: \(bookFocusedWindow)")
guard let focusedWindowElement = bookFocusedWindow as! AXUIElement? else {
fatalError()
}
var windowRole: AnyObject?
let windowRoleError = AXUIElementCopyAttributeValue(focusedWindowElement, "AXRole" as CFString, &windowRole)
print("windowRole error: \(windowRoleError.rawValue)")
print("windowRole: \(windowRole)")
var children: AnyObject?
let childrenError = AXUIElementCopyAttributeValue(focusedWindowElement, "AXChildren" as CFString, &children)
print("children error: \(childrenError.rawValue)")
print("children: \(children)")
输出:
query book role error: 0
book role: Optional(AXApplication)
book focused window error: 0
book focused window: Optional(<AXUIElement 0x7fc6acd28280> {pid=17149})
windowRole error: 0
windowRole: Optional(AXWindow)
children error: -25205
children: nil
-25205
错误代码与attribute unsupported code匹配。
我检查了窗口元素支持的属性列表,AXChildren就是其中之一。
var windowAttributes: CFArray?
let windowAttributesError = AXUIElementCopyAttributeNames(focusedWindowElement, &windowAttributes)
print("query window attributes error: \(windowAttributesError.rawValue)")
print("window attributes: \(windowAttributes)")
...
AXProxy,
AXDefaultButton,
AXMinimized,
AXChildren,
AXRole,
AXParent,
AXTitleUIElement,
AXCancelButton,
AXModal,
...
这种行为真的很奇怪,因为辅助功能检查器显示了窗口元素的子元素:
发布于 2021-04-06 21:44:00
事实证明,解决方案是使用AXUIElementCopyAttributeValues
。除了这个之外,AXUIElementCopyAttributeValue
已经为我的所有应用程序工作过了。
var children: CFArray?
let childrenError = AXUIElementCopyAttributeValues(focusedWindowElement, "AXChildren" as CFString, 0, 999, &children)
print("children error: \(childrenError.rawValue)")
print("children: \(children)")
https://stackoverflow.com/questions/66969764
复制相似问题