I have the need to detect multiple-key combinations from the user in the delicious:designer. While porting the designer to ActionScript 3 I decided to refine this behavior and came across this post with an ActionScript 2 class for detecting multi-key combos. I ported this class to AS3, borrowed this other class to replace the missing Key.isDown() function in AS3, and wrote a custom KeyComboEvent event class to create a rather nice multi-key detection system that will allow for far greater flexibility than the current (build 38) key detector.This is all that is needed to create and listen for multiple-key combinations in ActionScript 3
import com.Keyboard.*;
import flash.events.*;// Key is used so we can test for a key being down, like we used to do in AS2Key.initialize(stage);
// Create your key detector and set up a few combinations to test for
var keyDet = new KeyDetection(stage);keyDet.addCombination(“undo”, Keyboard.CONTROL, 90);
// Control + ZkeyDet.addCombination(“redo”, Keyboard.CONTROL, 89);
// Control + YkeyDet.addCombination(“three keys”, Keyboard.CONTROL, Keyboard.SHIFT, 89);
// Control + Shift + Y
// Add a listener so we can respond to key combinations when they are pressed
keyDet.addEventListener(KeyComboEvent.KEY_COMBINATION, keyCombo);
function keyCombo(event:KeyComboEvent):void
{
switch (event.label)
{
case “undo”:
trace(“Undo Combination Pressed”);
textArea.appendText(“Undo Combination Pressedn”);
break;
case “redo”:
trace(“Redo Combination Pressed”);
textArea.appendText(“Redo Combination Pressedn”);
break;
case “three keys”:
trace(“Our three-key Combination was Pressed”);
textArea.appendText(“Our three-key Combination Pressedn”);
break;
}
}
}
Click here to download the Flash 9 sample with source code, and click here to view the package documentation.
