Liam Flaherty
Liam Flaherty

Reputation: 337

Convert key code to string in Actionscript 3

I am using Actionscript 3 in Flash CS6 using the Adobe AIR 3.4 for Desktop runtime.

I have certain key codes defined as integer values (example below returns 38 for UP and 68 for D)

var KEY_UP:uint = Keyboard.UP;
var KEY_D:uint = Keybaord.D;

However, I need to display the keys to the keys to the user (and obviously cannot display the integer values).

How can I convert these keyboard values to a string value such as "Up" or "D" (instead of 38 and 68)?

Upvotes: 2

Views: 2982

Answers (2)

AturSams
AturSams

Reputation: 7962

If you are using OpenFL with Haxe, you can go to Keyboard.hx in openfl/ui and use a regexp in a text editor (like Vim or Gedit) on the contents of the file to generate a keyCode to string dictionary.

Use this to create a switch:

:%s/\([A-Z_0-9]*\)\ =\ \([0-9]*\)/case \2\: return "\1"/g

Upvotes: 1

ton
ton

Reputation: 1624

You can get property name with describeType, and access property as String such as Keyboard["UP"].

So, you can create table. For example

import flash.utils.describeType;

function getKeyboardDict():Dictionary {
    var keyDescription:XML = describeType(Keyboard);
    var keyNames:XMLList = keyDescription..constant.@name;

    var keyboardDict:Dictionary = new Dictionary();

    var len:int = keyNames.length();
    for(var i:int = 0; i < len; i++) {
        keyboardDict[Keyboard[keyNames[i]]] = keyNames[i];
    }

    return keyboardDict;
}

var keyDict:Dictionary = getKeyboardDict();

trace(keyDict[Keyboard.UP]); //UP
trace(keyDict[Keyboard.SHIFT]); //SHIFT

Upvotes: 7

Related Questions