【问题标题】:Applescript: How to select menu items in background application?Applescript:如何在后台应用程序中选择菜单项?
【发布时间】:2015-08-04 06:52:50
【问题描述】:

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

目前我的代码是:

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"

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

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

我需要改变什么?

谢谢。

【问题讨论】:

    标签: macos applescript


    【解决方案1】:

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

    【讨论】:

    • 这确实有效,谢谢。中文的标识符是:zh_Hans_CN。但是您说脚本要求应用程序位于前台,但我可以成功使用我的代码而无需将其带到前台。它只需要之前在某个时候被带到前台。
    • 你确实比我解决问题的方式更有效地解决了我的问题。但是假设我打开系统偏好设置,然后打开 Chrome,然后打开我的原始脚本并运行它,它仍然会成功更改语言。有一个奇怪的怪癖/故障,您可以在顶部应用程序中看到菜单项也发生变化。
    • 可能在少数情况下,但 GUI 脚本只有在受影响的应用程序处于前台而不失去焦点的情况下才能可靠地工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多