Multiple–Key Combination Detection

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.

2 Responses to “Multiple–Key Combination Detection”

  1. Randy Carr Says:

    Simply does not work on the Mac. The control / command key is filtered and when that happens, the char code is modified thereby not calling key detection handler. :(

  2. Jon Beebe Says:

    Unfortunately that is a problem on the Mac. I have been able to get ‘control’ to work on the Mac, but not with any regularity. I do not know why this is and have yet to find a complete and fail-safe solution. However this does work on the P.C.

Leave a Reply