3

I tried to use the following to open the Spotlight search box:

tell application "System Events"
    keystroke " " using {command down}
end tell

It simply tries to issue command-space. It does work, but if I save the script as an Application and run it, the Spotlight window shows up and then promptly disappears afterwards.

Why does this happen and what can I do to keep the Spotlight window open?

Alternatively: How do I open the Spotlight search box using Applescript?

Snoqual
  • 573
  • 6
  • 11

2 Answers2

2

Your script opens the Spotlight menu. The keyboard shortcut for opening the Spotlight window is command + option + space...

tell application "System Events" to keystroke space using {command down, option down}

UPDATE: Given your revised answer, I have composed a little script that should do what you want...

set the searchText to the text returned of (display dialog "Enter the name of an item you wish to search for in Spotlight:" default answer "")
tell application "System Events"
    keystroke space using {command down}
    keystroke the searchText
    --[1]
end tell

You can do one of the following things at [1]:

  • Open the top hit:

    keystroke return using {command down}
    
  • Move the selection to the first item in the next category:

    keystroke (ASCII character 31) using {command down} --down arrow
    
  • Move the selection to the first item in the previous category:

    keystroke (ASCII character 30) using {command down} --up arrow
    
  • Move the selection to the first item in the whole menu:

    keystroke (ASCII character 31) using {control down}
    
  • Move the selection to the last item in the whole menu:

    keystroke (ASCII character 30) using {control down}
    
fireshadow52
  • 6,298
  • 2
  • 30
  • 46
  • Okay. Wrong terminology. I'm looking for the script to open the _menu_. – Snoqual Aug 04 '11 at 05:20
  • Does this mean that it is not possible to keep the Spotlight search box open with Applescript? What I'm looking for is not to have another window. I want to open the Spotlight search box and have the cursor in the search box, ready for user input. – Snoqual Aug 05 '11 at 00:45
  • As far as I know you can't keep the Spotlight window open with Applescript. I'm sorry. Have you tried my script yet? – fireshadow52 Aug 05 '11 at 16:23
  • For me it works: osascript -e 'tell application "System Events" to keystroke space using {command down} ' – Michał Ziobro Aug 27 '16 at 20:14
0

Simple add a delay.

     tell application "System Events"
         keystroke " " using {command down}
         delay 5
         delay 5
     end tell

Or to foolproof this:

S.Doe_Dude
  • 151
  • 1
  • 5