在Applescript中,如何确定菜单项是否被选中/聚焦?

Kev*_*ner 5 macos applescript focus menu

我有一个OS X 10.5脚本,它将搜索框的焦点集中在任何应用程序的"帮助"菜单中.我有一个关键组合,就像Spotlight一样,我希望它在我运行脚本时切换.因此,我想检测搜索框是否已经集中用于键入,如果是,请键入Esc而不是单击"帮助"菜单.

这是现在的脚本:

tell application "System Events"
    tell (first process whose frontmost is true)
        set helpMenuItem to menu bar item "Help" of menu bar 1
        click helpMenuItem
    end tell
end tell
Run Code Online (Sandbox Code Playgroud)

而我正在考虑这样的事情:

tell application "System Events"
    tell (first process whose frontmost is true)
        set helpMenuItem to menu bar item "Help" of menu bar 1
        set searchBox to menu item 1 of menu of helpMenuItem
        if (searchBox's focused) = true then
            key code 53 -- type esc
        else
            click helpMenuItem
        end if
    end tell
end tell
Run Code Online (Sandbox Code Playgroud)

...但我收到此错误:

应用程序"系统事件"的应用程序"脚本编辑器"的菜单栏1的菜单栏项"帮助"的菜单"帮助"的菜单项目1无法集中.

那么有没有办法让我的脚本检测搜索框是否已经集中?


我通过解决它解决了我的问题.我仍然不知道如何检查菜单项是否被选中,所以我将打开这个主题.

小智 5

您需要使用属性AXMenuItemMarkChar

\n\n

例子:

\n\n
tell application "System Events"\n    tell process "Cisco Jabber"\n        set X to (value of attribute "AXMenuItemMarkChar" of menu item "Available" of menu "Status" of menu item "Status" of menu "File" of menu bar item "File" of menu bar 1) is "\xe2\x9c\x93" -- check if Status is "Availible"    \n    end tell\nend tell\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果菜单项被选中,则返回值为\xe2\x9c\x93,否则为missing value

\n\n

注意:仅当正在检查其菜单的应用程序当前位于最前面时,此测试才有效时,此测试才有效。

\n


tjw*_*tjw 3

使用 /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app 您可以使用内置的辅助功能系统来查看鼠标下 UI 元素的属性。请特别注意将焦点锁定在元素上的 cmd-F7 操作和“刷新”按钮。遗憾的是,元素和属性名称与脚本套件中的名称不直接匹配,但您可以查看系统事件字典或通常猜测正确的术语。

使用它您可以确定两件事。首先,该focused属性不在 上menu item,而是text field在 内有一个menu item焦点。其次,菜单项有一个selected属性。

有了这个,我想出了:

tell application "System Events"
    tell (first process whose frontmost is true)
        set helpMenuItem to menu bar item "Help" of menu bar 1

        -- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact.
        set searchBox to a reference to menu item 1 of menu of helpMenuItem
        set searchField to a reference to text field 1 of searchBox

        if searchField's focused is true then
            key code 53 -- type esc
        else
            click helpMenuItem
        end if
    end tell
end tell
Run Code Online (Sandbox Code Playgroud)

虽然这仍然行不通。据我所知,关键事件并未触发,因此focused文本字段上的属性可能仍然存在问题。

不管怎样,你的click再次解决方案似乎更容易。