Skip navigation
Currently Being Moderated

How do I assign a keyboard event to a button?

Aug 19, 2012 1:34 AM

Tags: #flash #keyboard-event #as3 #button #action #3 #code_snippets #actionscript #keyboard #event #as3.0 #ac3 #actionscript3 #function



I am umbilical cord new to flash cs4 (as3) and I want to know how I can make a a keyboard event enable a button to be pressed. Specifically, I am making a soundboard in which you click on a button and a sound is played. I want to make it so when you press a SPECIFIC key on the keyboard, the button is pressed so then the sound is played.


P.S. I would really just like a straightforward answer and possibly a code I could copy and paste.


I am using Flash CS4 with Actionscript 3.0


Thank you!

  • Currently Being Moderated
    Aug 19, 2012 4:42 AM   in reply to jasonnesmit

    You cannot press a button using code.  You could make the button as a movieclip and have it animate like it is being pressed, but the keyboard code would need to trigger the sound as well.

    Mark as:
  • Currently Being Moderated
    Aug 19, 2012 5:20 AM   in reply to jasonnesmit

    Just use a


    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);


    function keyPressed(event:KeyboardEvent):void {


         if(event.keyCode == ???){

              // play the sound




    Where I show the "???" you would replace with the keyCode for the key you want pressed for that sound.  To determine the keyCode you can use the trace line that I have commented out.


    Note that when testing in Flash you often need to disable the keyboard shortcuts in the Flash Player in order to be able to use alot of the keys.  You will find this option in the Control menu options in the player.

    Mark as:
  • Currently Being Moderated
    Aug 20, 2012 4:30 AM   in reply to jasonnesmit

    You should try to learn how to find answers yourself.  Try Googling "AS3 Sound tutorial" and you should be able to find a little code that will do what you need.  The help documentation is also a great resource for information and examples.

    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points