Shan’s Simple Examples: Keyboard shortcuts and TextInput

Someone on #flex asked about preventing text from appearing in a TextInput or TextArea, when the user is using a keyboard shortcut. After a little discussion, I came up with a working example. I decided to use shift-space to simplify things.

The first assumption is that you’re listening for keyboard shortcuts at the application level:

1
application.addEventListener(KeyboardEvent.KEY_UP,shortcutHandler);

Now, you’ve got your input box, and it’s listeners:

1
<mx:TextArea height="100%" width="95%" keyDown="shortcutPreprocess(event)" textInput="shortcutPreventer(event)"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private function shortcutPreprocess(e:KeyboardEvent):void {
    if (e.shiftKey && e.keyCode == 32) {
        _isShiftSpace = true;
    } else {
        _isShiftSpace = false;
    }
}

private function shortcutPreventer(e:Event):void {
    if (_isShiftSpace) {
        e.stopImmediatePropagation();
        e.preventDefault();
    }
}

Note that I had to set a boolean in my shortcutPreprocess method, and then I check for the boolean in shortcutPreventer. The reason being is that the textInput event doesn’t pass in the KeyboardEvent in any way, so I don’t know if there was a key combo pressed.

Working example & source:
http://www.iotashan.com/examples/KeyboardShortcut/

Comments