MacOS – How to make selection from AppleScript dialog list with keystroke

applescriptkeyboardmacosshortcut

I've created an application with AppleScript in Automator.

The application, right off the bat, presents the user with a dialog list.

By default, there are two ways to select an item from the list:

  1. Using your mouse.

  2. Using the arrow keys on your keyboard.

However, what I would like to do is offer the user a third option: to select the item based on a keystroke or keyboard shortcut. I would also like the selected item to be submitted directly after the keystroke or keyboard shortcut is pressed.

For example:

on run {input, parameters}

    set FruitList to {"Banana (#1)", "Kiwi (#2)", "Mango (#3)", "Coconut (#4)", "Pear (#5)"}

    set FavoriteFruitAnswer to choose from list FruitList with title "Fruit Dialog" with prompt "What's your favorite fruit?" default items "Banana (#1)"


    if FavoriteFruitAnswer is false then
        error number -128 (* user cancelled *)
    else
        set FavoriteFruitAnswer to FavoriteFruitAnswer's item 1 (* extract choice from list *)
    end if

    return input
end run

The preceding code produces the following:

What I want to occur is if the user presses the number "2" on their keyboard, therefore "Kiwi (#2)" is selected and then the "OK" button is automatically pressed. If the user presses the number "4" on their keyboard, therefore "Coconut (#4)" is selected and then the "OK" button is automatically pressed. And so on.

Is this possible?

What I know is possible is to create a dialog box with a text field where the user types in the number manually and then the user hits enter manually and the number is assigned to the corresponding fruit type.

But that's not a particularly pretty solution.

Best Answer

AppleScript is not robust enough to do exactly what you're asking, however if you want to be able to select by number then put the number ahead of the name of the fruit, although enter will still need to be pressed after the number is pressed. Otherwise, pressing whatever the first character of the list item entry is will select it too.

For example, change the following two lines of code from:

set FruitList to {"Banana (#1)", "Kiwi (#2)", "Mango (#3)", "Coconut (#4)", "Pear (#5)"}
set FavoriteFruitAnswer to choose from list FruitList with title "Fruit Dialog" with prompt "What's your favorite fruit?" default items "Banana (#1)"

To:

set FruitList to {"1. Banana", "2. Kiwi", "3. Mango", "4. Coconut", "5. Pear"}
set FavoriteFruitAnswer to choose from list FruitList with title "Fruit Dialog" with prompt "What's your favorite fruit?" default items "1. Banana"

As a side note, double-clicking a list entry to select it with the mouse does also trigger the enter key press automatically.