在Applescript中,如何确定菜单项是否已选择/集中显示?

时间:2020-03-05 18:55:03  来源:igfitidea点击:

我有一个用于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

我在想这样的事情:

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

...但是我得到这个错误:

Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.

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

我通过解决它解决了我的问题。我仍然不知道如何检查菜单项是否被选中,因此我将保持打开此主题的状态。

解决方案

回答

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

使用这个可以确定两件事。首先," focused"属性不在" menu item"上,而是在" menu item"内有一个" text field"被聚焦。其次,菜单项具有" 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

虽然这仍然行不通。据我所知,关键事件并未触发,因此文本字段上的" focused"属性可能仍然有些棘手。

无论如何,再次执行"单击"解决方案似乎要容易得多。

回答

内置的快捷键" Cmd-?"(Cmd-Shift- /)已经具有这种功能。如果尚未聚焦,它将关键焦点移至帮助菜单的搜索字段,否则关闭菜单。

回答

我只是碰巧需要自己在Illustrator中进行一些文件处理。

这是我想出的:

tell application "Adobe Illustrator"
activate
tell application "System Events"
    tell process "Illustrator"
        set frontmost to true
        set activeMenuItem to enabled of menu item "Unlock All" of menu "Object" of menu bar item "Object" of menu bar 1
        if activeMenuItem is true then
            tell me to beep 3
        else
            tell me to beep 2
        end if
    end tell
end tell
end tell

完毕。

这没有问题,可以用于迭代文件。在未来的自动化过程中,我可能必须做很多次。

祝你好运!