gajera sanjay
gajera sanjay

Reputation: 107

How can I map ASCII values to appropriate key codes?

How can I map ASCII values to appropriate key codes?

Upvotes: 1

Views: 1414

Answers (2)

Mitch Wheat
Mitch Wheat

Reputation: 300719

Key Codes are defined for common keys. They are prefixed by VK_ (for virtual key):

Alphanumeric keys

VK_0, VK_1, ..., VK_9, VK_A, VK_B, ..., VK_Z

Control keys

VK_ENTER, VK_BACKSPACE, VK_TAB, VK_ESCAPE

Function keys

VK_F1, VK_F2, VK_F3, VK_F4 VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, VK_SCROLL_LOCK, VK_PRINTSCREEN, VK_PAUSE, VK_DELETE, VK_INSERT, VK_PAGE_UP, VK_PAGE_DOWN, VK_HOME, VK_END

Arrow keys

VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN

Ref. : Java Notes: Keyboard

Upvotes: 4

akf
akf

Reputation: 39495

If i understand correctly, you are coming up with a message you want to broadcast as KeyEvents, and converting the message to ASCII is simple enough. now you want us to convert that ACSII to keycodes.

if you look at the code for KeyEvent, you will see that the VK_A through VK_Z equate to the ASCII values of A through Z which makes mapping relatively easy. note that though these are ASCII for the uppercase letters, unmodified in the KeyEvent they represent the lowercase letters. to get the uppercase keycodes, you need to combine the modifiers for VK_SHIFT (and/or VK_CAPSLOCK) with the ASCII for the uppercase letter.

so, continuing with the assumed goal, you can create a KeyEvent by setting the keycode for a letter by resolving both the lowercase and the uppercase to the same ASCII code (for the uppercase). you can then set the modifier on the KeyEvent to VK_SHIFT if your input ASCII falls withing the range of the uppercase ASCII range.

if your problem area is more extensive, you may want to setup a Map with which you can look up these codes, as well as other punctuation and control chars. The implementation of KeyEvent.getKeyText() shows something similar, but in the opposite direction. you can use that as your starting point. going down this route will also reduce risk to your app if, for some reason, Java decides to change the constant values for these VK_ fields.

Upvotes: 0

Related Questions