AS3 – Detecting Control, Shift and Alt keyboard shortcuts

Here is a snippet of code which allows you to detect keyboard shortcuts such as ctrl+[another key] and ctrl+shift+[another key]. I wasn’t able to find any decent examples of detecting shortcuts but after reading the AS3 documentation I found that the Keyboard event contains the following boolean properties [cc lang=”actionscript3″]
ctrlKey
shiftKey
altKey
[/cc]
So by simply checking if those properties a true you can fire code after a combination was pressed.

The following detects ‘ctrl+p’:

[cc lang=”actionscript3″]
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyBoardUp);

function onKeyBoardUp(e:KeyboardEvent):void
{
if ( e.ctrlKey ) //if control key is down
{
switch ( e.keyCode )
{
case Keyboard.P : //if control+p
//do something
break;
}
}
}
[/cc]

You can also detect ctrl+[another key] and ctrl+shift+[another key] at the same time by using:

[cc lang=”actionscript3″]
function onKeyBoardUp(e:KeyboardEvent):void
{
if ( e.ctrlKey ) //if control key is down
{
if ( e.shiftKey ) //if shift key is also down
{
switch ( e.keyCode )
{
case Keyboard.U : //if control+shift+u
//do something
break;
}
}
else //otherwise do normal control shortcut
{
switch ( e.keyCode )
{
case Keyboard.P : //if control+p
//do something
break;
}
}
}
}
[/cc]


Comments

2 responses to “AS3 – Detecting Control, Shift and Alt keyboard shortcuts”

  1. Hey guys,
    im trying to do the key combinations the same way- just with regular buttons instead.
    When i use this code however, Flash does not detect the second button press in the combo.
    please let me know what I am doing wrong.

    //=========================================================//

    stage.addEventListener(KeyboardEvent.KEY_UP, onKeyBoardUp);
    function onKeyBoardUp(e:KeyboardEvent):void
    {
    if ( e.keyCode==Keyboard.S) //if S key is down
    {
    trace(“s is the best”);
    switch (e.keyCode )
    {
    case Keyboard.P: //if S+P
    //do something
    trace(“S P is pressed”);
    break;
    }
    }
    }

    thanks guys!

    1. Hi Darkin

      Since there is no built in way to detect if simultaneous normal keys are pressed you would have to do it manually by storing the key’s state in variable – something like this:

      var _sDown:Boolean = false;

      stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyBoardDown);
      stage.addEventListener(KeyboardEvent.KEY_UP, onKeyBoardUp);

      function onKeyBoardDown(e:KeyboardEvent):void
      {
      if (e.keyCode == Keyboard.S)
      {
      _sDown = true;
      }
      }

      function onKeyBoardUp(e:KeyboardEvent):void
      {

      switch (e.keyCode)
      {
      case Keyboard.S :
      _sDown = false;
      break;
      case Keyboard.P :
      if (_sDown)
      {
      // S+P are both down
      }
      break;

      }
      }

Leave a Reply