如何创建一个 Applescript 来设置键盘快捷键?

How to create an Applescript to set a Keyboard shortcut?

如果有人可以帮助我,我正在尝试为一些 服务.
自动创建键盘快捷键 到目前为止我得到的是

tell application "System Preferences"
    activate
    set current pane to pane id "com.apple.preference.keyboard"
    delay 1
    tell application "System Events"
        click radio button "Shortcuts" of tab group 1 of window "Keyboard" of application process "System Preferences"
        delay 1
        select row 6 of table 1 of scroll area 1 of splitter group 1 of tab group 1 of window 1 of application process "System Preferences"
        set value of text field 1 of UI element "My Service Name" of row 59 of outline 1 of scroll area 2 of splitter group of tab group 1 of window 1 of application process "System Preferences" to "⌥⌘1"
    end tell
end tell

但现在我卡住了,我不能做的是:

有人提示我该如何解决这个问题吗?

如果有其他方法可以在没有 applescript 的情况下创建快捷方式,欢迎使用

提前谢谢大家。

我稍微调整了您的脚本,因为我更喜欢分层 'tell block' 结构(我发现它更容易阅读和遵循),并且我已将其全部放入一个处理程序中以对其进行概括.但除此之外,诀窍是使用 where 搜索查看 UI 结构并找到可识别的特征(N.B,where 是更传统的 whose).请参阅脚本中的评论。请注意,我正在更改键盘快捷键首选项 "Spotlight" 部分中的 "Show Finder search window" 行,但通过更改处理程序调用的值,您可以更改任何首选项。

要完成这项工作,您需要知道您的服务属于哪个部分,以及列表中显示的服务名称。如果你为 new_val 输入一个文本字符串,它会把它当作你输入的第一个字母;如果你输入一个整数,它将把它当作一个键码,允许你使用非打印字符和功能键作为快捷方式。参见:list of key codes.

此脚本已更正,修复了几个错误,并适应了 'Services' 部分的层次结构,并且能够通过单击 'Add Shortcut' 按钮添加新的快捷方式.请注意,如果您是第一次添加快捷方式,UI 仍会显示 'Add Shortcut' 按钮,直到您 select 另一行。即使手动添加快捷方式也是如此,所以这是 GUI 的限制,而不是脚本。

-- sets the 'Send Message' shortcut to cmd-opt-A
my change_shortcut("Services", "Text", "Send Message", "a", {"command", "option"})
-- sets the 'Call' service shortcut to cmd-F6
my change_shortcut("Services", "Text", "Call", 97, {"command"})

on change_shortcut(shortcut_region, section_name, shortcut_title, new_val, special_key_list)
    tell application "System Preferences"
        activate
        set current pane to pane id "com.apple.preference.keyboard"
        delay 1
        tell application "System Events"
            tell process "System Preferences"'s window "Keyboard"'s first tab group
                click radio button "Shortcuts"
                tell first splitter group
                    set sidebar_obj to first table of first scroll area
                    tell sidebar_obj

                        (* 
                            this looks to find the first row in the sidebar that contains a static text 
                            element with the value of `shortcut_region`
                        *)

                        set sidebar_entry to first row where (its first static text's value is shortcut_region)
                        select sidebar_entry
                    end tell
                    set outline_obj to first outline of second scroll area
                    tell outline_obj

                        (* 
                            if the shortcut outline view is arranged in groups, this section 
                            finds the correct group and make sure its disclosure triangle is 
                            opened, exposing the settings within
                        *)

                        if section_name is not "" and section_name is not missing value then
                            set wanted_section_row to first row where (its last UI element's name is section_name)
                            tell wanted_section_row's second UI element
                                set disclosure_tri to first UI element whose role description is "disclosure triangle"
                                if disclosure_tri's value is 0 then click disclosure_tri
                            end tell
                            delay 0.5
                        end if

                        (* 
                            this looks to find the first row in the outline that contains two 
                            UI elements (the row's cells) the second of which contains a static text 
                            element with the value of shortcut_title
                        *)

                        set wanted_entry to first row where (its last UI element's name is shortcut_title)
                        tell wanted_entry
                            select
                            set new_shortcut_flag to false
                            tell second UI element
                                if exists button "Add Shortcut" then
                                    click button "Add Shortcut"
                                    set new_shortcut_flag to true
                                end if
                                UI elements

                                -- set up a list of special keys
                                set special_keys to {}
                                if special_key_list contains "command" then set end of special_keys to command down
                                if special_key_list contains "control" then set end of special_keys to control down
                                if special_key_list contains "option" then set end of special_keys to option down
                                if special_key_list contains "shift" then set end of special_keys to shift down

                                -- opens the text field for editing, then write or keycode in the text
                                tell first text field
                                    if not new_shortcut_flag then perform action "AXConfirm"
                                    if class of new_val is text then
                                        keystroke new_val using special_keys
                                    else
                                        key code new_val using special_keys
                                    end if
                                end tell
                                -- select the cell to submit the result
                                select
                            end tell
                        end tell
                    end tell
                end tell
            end tell
        end tell
    end tell
end change_shortcut

我唯一确定的方法是使用 UI 脚本 系统偏好设置 > Keyboard > Shortcuts > Services(或 Shortcuts 下的任何其他类别)本质上是模拟手动执行时会发生的所有步骤。这就是为什么如果没有其他方法可以完成手头的任务,我只会使用 UI 脚本

由于在您的 代码 中,您正在使用 select row 6 ... 并希望定位 row 59,我假设您正在使用 macOS MojavemacOS Catalina,并针对 Services category,因为那是唯一一个 类别 实际上有那么多 ,或更多,分配一个 键盘快捷键 .

示例 AppleScript 代码,进一步显示在Script Editor macOS MojavemacOS Catalina,以及 macOS High Sierra 稍作修改,按原样工作,在我的系统上使用 美国英语 语言和地区[= 系统偏好设置.

中的 99=] 设置

这也是专门针对 服务 类别 编写的,因为其他 类别 需要不同 编码.

您将需要设置三个变量的serviceNameregularKeymodifierKeys,后者是根据script开头的listcomments .

它最初设置为 导入图像 使用 键盘快捷键 ⇧⌘9 和你应在修改 脚本 之前按原样对其进行测试。

注意:任何 键盘快捷键 集对于在 键盘快捷键 被按下。

示例 AppleScript 代码:

--  # Call the SetChangeServicesKeyboardShortcut(serviceName, regularKey, modifierKeys)
--  # handler using the parameters as defined below:

--  # serviceName defines the name of the target service under:
--  # System Preferences > Keyboard > Shortcuts > Services

--  # regularKey defines the regular key to press.

--  # modifierKeys define the modifier keys to be pressed. 
--  # Use the value based on the list below:
--  # 
--  #   1 = {command down}
--  #   2 = {shift down, command down}
--  #   3 = {control down, command down}
--  #   4 = {option down, command down}
--  #   5 = {control down, option down, command down}
--  #   6 = {shift down, control down, command down}
--  #   7 = {shift down, option down, command down}
--  #   8 = {shift down, control down, option down, command down}
--  #   
--  # |  shift = ⇧ | control = ⌃ | option = ⌥ | command = ⌘ |
--  #   


my SetChangeServicesKeyboardShortcut("Import Image", "9", "2")



--  ##################################
--  ## Do not modify code below unless necessary, as ##
--  ## it's tokenized for the variables defined above.   ##
--  ##################################


--  ## Handlers ##

on SetChangeServicesKeyboardShortcut(serviceName, regularKey, modifierKeys)
    --  # Need to start with System Preferences closed.
    if running of application "System Preferences" then
        try
            tell application "System Preferences" to quit
        on error
            do shell script "killall 'System Preferences'"
        end try
    end if
    repeat while running of application "System Preferences" is true
        delay 0.1
    end repeat
    --  # Open System Preferences to the target pane.
    tell application "System Preferences"
        activate
        reveal pane id "com.apple.preference.keyboard"
    end tell
    --  # Navigate to Shortcuts > Services and select the
    --  # target service, then change/set its keyboard shortcut.
    tell application "System Events"
        tell application process "System Preferences"
            tell its window 1
                --  # Wait until the Shortcuts tab can be clicked.          
                repeat until exists (radio buttons of tab group 1)
                    delay 0.1
                end repeat
                --  # Click the Shortcuts tab.          
                click radio button "Shortcuts" of tab group 1
                --  # Wait until Services can be selected.                      
                repeat until exists ¬
                    (rows of table 1 of scroll areas of splitter group 1 of tab group 1 ¬
                        whose name of static text 1 is equal to "Services")
                    delay 0.1
                end repeat
                --  # Select Services.          
                try
                    select (rows of table 1 of scroll area 1 of splitter group 1 of tab group 1 ¬
                        whose name of static text 1 is equal to "Services")
                end try
                tell outline 1 of scroll area 2 of splitter group 1 of tab group 1
                    --  # Wait until the services under Services are available.                 
                    repeat until exists (row 1)
                        delay 0.01
                    end repeat
                    --  # Set focus to the first item of Services.              
                    repeat 2 times
                        key code 48 -- # tab key
                        delay 0.25
                    end repeat
                    --  # Get the name of every service under Services.             
                    set serviceNames to (get name of UI element 2 of rows)
                    --  # Get the row number of the target service under Services.              
                    set countRows to (count serviceNames)
                    repeat with i from 1 to countRows
                        if contents of item i of serviceNames is equal to serviceName then
                            set rowNumber to i
                            exit repeat
                        end if
                    end repeat
                    --  # Select the row of the target target service under Services.               
                    select (row rowNumber)
                    --  # Change/Set the keyboard shortcut of the target service under Services.                
                    if exists (button "Add Shortcut" of UI element 2 of row rowNumber) then
                        click button "Add Shortcut" of UI element 2 of row rowNumber
                        my shortcutKeystrokes(regularKey, modifierKeys)
                    else
                        key code 36 -- # return key
                        my shortcutKeystrokes(regularKey, modifierKeys)
                    end if
                    select (row 1)
                end tell
            end tell
        end tell
    end tell
    quit application "System Preferences"
end SetChangeServicesKeyboardShortcut

on shortcutKeystrokes(regularKey, modifierKeys)
    tell application "System Events"
        if modifierKeys is equal to "1" then
            keystroke regularKey using {command down}
        else if modifierKeys is equal to "2" then
            keystroke regularKey using {shift down, command down}
        else if modifierKeys is equal to "3" then
            keystroke regularKey using {control down, command down}
        else if modifierKeys is equal to "4" then
            keystroke regularKey using {option down, command down}
        else if modifierKeys is equal to "5" then
            keystroke regularKey using {control down, option down, command down}
        else if modifierKeys is equal to "6" then
            keystroke regularKey using {shift down, control down, command down}
        else if modifierKeys is equal to "7" then
            keystroke regularKey using {shift down, option down, command down}
        else if modifierKeys is equal to "8" then
            keystroke regularKey using {shift down, control down, option down, command down}
        end if
    end tell
end shortcutKeystrokes

注意:对于 macOS High Sierra,可能更早,在 评论 -- # Set focus to the first item of Services. 下设置 repeat 2 times至:repeat 3 times


注意:示例 AppleScript code 就是这样, , 没有现有的 错误处理 ,不包含任何额外的 错误处理 可能是适当的。用户有责任根据需要或需要添加任何 错误处理 。查看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay 命令 在适当的事件之间可能是必要的,例如delay 0.5,适当设置延迟