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

Applescript: How to select menu items in background application?

我的最终目标是在后台启动系统偏好设置,转到听写和语音,更改听写语言,然后退出系统偏好设置。都在后台,都没有人看到。

目前我的代码是:

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"

我注意到如果我在 focus/as 选定的顶级进程中有我的系统偏好设置,这会起作用。之后,可以选择任何应用程序,此代码将起作用。或者,如果我将 "launch" 更改为 "activate",它将起作用(但这违背了我的目的,因为它将系统偏好设置置于顶部)

但是,如果系统偏好设置尚未启动,如果这是 运行,我的代码将 无法工作 。就像系统在 selected/activated.

之前对应用程序及其菜单一无所知

我需要更改什么?

谢谢。

首先,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