Can AppleScript automatically press a key for me in an application? I'm trying to devices an AppleScript that will automatically press the right arrow key for 1 second, then the left arrow key for 1 second and repeat this in an endless loop until I interrupt it.

Here is what I've come up with so far, but it's not quite working:

tell application "VisualBoyAdvance"
    repeat 100 times
        tell application "VisualBoyAdvance" to keystroke "124"
        delay 1
    end repeat     
end tell
You could repeat key code commands until the frontmost application changes:

delay 1
activate application "TextEdit"
tell application "System Events"
    repeat while (path to frontmost application) is (path to application "TextEdit")
        repeat 3 times
            key code 123
            delay 0.3
        end repeat
        repeat 3 times
            key code 124
            delay 0.3
        end repeat
    end repeat
end tell


Shorter delays (including 0.2 seconds) made it difficult to stop the script. I had to hold ⌥⇧⌘⎋ to force quit TextEdit.

This moved left only once:

delay 1
tell application "System Events"
    key down (character id 28)
    delay 5
    key up (character id 28)
end tell



left: 123 / 28
right: 124 / 29
down: 125 / 31
up: 126 / 30