Applescript:如何在后台应用程序中选择菜单项?

时间:2015-08-04 06:52:51

标签: macos applescript

我的最终目标是在后台启动系统偏好,转到听写和放大演讲,改变听写语言,然后退出系统偏好。一切都在后台,都没有人看到。

目前我的代码是:

tell application "System Preferences" to launch
delay 1
tell application "System Events" to tell process "System Preferences"
    click menu item "Dictation & Speech" of menu "View" of menu bar 1
    tell pop up button 1 of tab group 1 of window 1
        click
        if value is "English (United States)" then
            click menu item "Chinese (China)" of menu 1
        else
            click menu item "English (United States)" of menu 1
        end if
    end tell
end tell
quit application "System Preferences"

我注意到,如果在某些时候我将我的系统偏好设置为焦点/作为选定的顶级过程,这是有效的。之后,可以选择任何应用程序,此代码将起作用。或者,如果我将“启动”更改为“激活”,它将起作用(但这会失败我的目的,因为它将系统偏好设置置于顶部)

但是,如果在尚未启动“系统偏好设置”的情况下运行此代码,则我的代码将 。这就像系统在选择/激活之前对应用程序及其菜单一无所知。

我需要改变什么?

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,GUI脚本总是要求受影响的应用程序位于前台。

这是一种解决方案,可以更改首选项文件中的相应键,并在必要时重新启动听写过程。不需要打开System Preferences

property localeIdentifiers : {"en_US", "zh_Hans_CN"}
property defaultsIdentifier : "com.apple.speech.recognition.AppleSpeechRecognition.prefs DictationIMLocaleIdentifier"

set currentLanguage to (do shell script "defaults read " & defaultsIdentifier)
if currentLanguage is item 1 of localeIdentifiers then
    set currentLanguage to item 2 of localeIdentifiers
else
    set currentLanguage to item 1 of localeIdentifiers
end if
do shell script "defaults write " & defaultsIdentifier & space & currentLanguage
do shell script "defaults write com.apple.assistant 'Session Language' " & currentLanguage
try
    do shell script "killall -HUP DictationIM"
end try