AS3 – Detecting Control, Shift and Alt keyboard shortcuts
12 years ago
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
1 2 3 | ctrlKey shiftKey altKey |
So by simply checking if those properties a true you can fire code after a combination was pressed.
The following detects ‘ctrl+p’:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } } } |
You can also detect ctrl+[another key] and ctrl+shift+[another key] at the same time by using:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } } } } |