使用 AppleScript 列出窗口中所有 UI 元素的名称(GUI 脚本)

问题描述 投票:0回答:2

一行摘要 - 我正在寻找一种方法让 AppleScript 本身显示它期望在“tell”语句中引用的特定窗口内容(UI 元素)的名称。

如何让 AppleScript 列出它希望我用来引用窗口内容的名称?

例如我可以说

tell current application to tell its front window's list 1 to ...

我正在尝试找出所有窗口内容的“列表 1”之类的术语,以便我可以将其与辅助功能检查器中的列表交叉引用..

我尝试了这段代码,但第一行生成一个错误,指出“错误”无法将应用程序\“系统事件\”的“class prcs”\“iTunes\”窗口1的“class ects”名称转换为字符串类型." 从 «class prcs» 窗口 1 的 «class ects» 名称“iTunes”中的数字 -1700 到字符串“

tell application "System Events" to tell process "iTunes" to set elementNames to the names of the entire contents of its front window as string
tell application "TextEdit"
    activate
    make new document at the front
    set the text of the front document to elementNames
    set WrapToWindow to text 2 thru -1 of (localized string "&Wrap to Window")
end tell
user-interface applescript ui-automation
2个回答
31
投票

在 GUI 脚本中,在 entire contents [of]

 应用程序上下文中的进程窗口上使用 
System Events
 将返回活动应用程序中最前面窗口()的所有 UI 元素(GUI 控件)的列表整个层次结构扁平化为列表):

tell application "System Events"
  tell front window of (first application process whose frontmost is true)
    set uiElems to entire contents
  end tell
end tell

如果您在

Script Editor
中运行上述内容,结果窗格将显示对象说明符的列表 - 例如,
button 1 of window "Main" of application process "Music" of application "System Events"
- 它不会直接显示特定信息,但您可以从中至少收集到类型 UI 元素的(类)(本例中为
button
)以及其相同类型同级元素中的 position (
1
)

例如,要定位音乐,请将

application process "Music"
替换为
(first application process whose frontmost is true)

请注意,如果您只想要直接子元素,则可以使用

UI elements [of]
代替
entire contents [of]
,并且您不仅可以将其应用于窗口(以获取顶级UI元素),还可以将其应用于窗口。到它包含的任何 UI 元素以获得子元素。


您无法像您尝试的那样通过将枚举转换为带有 as string

string
来提取这些元素的属性,但您可以在
repeat
循环中提取属性:

假设 names 指的是 class 名称(例如

table
button
),请尝试以下操作:

set classNames to {}
tell application "System Events"
    tell front window of (first application process whose frontmost is true)
        repeat with uiElem in entire contents as list
            set classNames to classNames & (class of uiElem as string)
        end repeat
    end tell
end tell

请注意,莫名其妙地需要

as list
(从 macOS 10.12.3 开始)才能完成这项工作(对于
UI elements [of]
则不需要)。

这将返回一个类名列表,例如

{"splitter group", "text field", "button", "scroll area", ... }
,但是,它本身不足以定位特定元素,因为层次结构已被展平。


0
投票

您还可以使用Xcode自带的Accessibility Inspector.app

© www.soinside.com 2019 - 2024. All rights reserved.