Keystroke

How do I send a keystroke to an app?

Hi benglett, and welcome to the forums.

You use System Events The keystroke command might go to System Events or it will go to an application process through System Events. For modifier keys you add “using (modifier key) down” as in

tell application "System Events" to keystroke "s" using command down

For multiple modifiers, “using (modifier key) down & (modifier key) down” as in

tell application "System Events" to tell process "Script Editor" to keystroke "s" using shift down & command down

This example was written mostly to amuse myself:

tell application "TextEdit"
	activate
	if not (exists window 1) then make new document
	repeat until exists window 1
		delay 0.1
	end repeat
	
	tell application "System Events"
		keystroke "Hello World!"
		delay 0.25
		keystroke "a" using command down --select all
		delay 0.25
		keystroke "|" using command down --center
		delay 0.25
		keystroke "b" using command down --bold
		delay 0.25
		repeat 5 times
			keystroke "+" using command down --make bigger
			delay 0.25
		end repeat
		keystroke "c" using command down --copy
		key code 124 --right arrow (end) to deselect, preventing deletion of the text
		delay 0.25
		keystroke return
		delay 0.25
		keystroke "v" using command down
		
		--the following will save the document if you have GUI scripting enabled
		
		delay 5 --pause to look
		tell process "TextEdit" --note that the keystroke command is going to a different process
			keystroke "S" using command down--or "s" using shift down & command down 
			delay 0.25
			keystroke "Hello World"
		end tell
		delay 1 --to allow time for type
		
		tell window 1 of process "TextEdit" to tell button "Save" of sheet 1 to click
		
	end tell
	
end tell