2

Is there any way to get the keycode of a char? For example

getKeycode('C');

Is there anything like that?

Thanks

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Stripies
  • 1,267
  • 5
  • 19
  • 29
  • 4
    the "keycode" *is* the `char`, eg `char c = 'A';` and `char c = 65;` are identical statements – Bohemian Dec 14 '11 at 12:40
  • What are these "keycodes" that you speak of? – NPE Dec 14 '11 at 12:45
  • This has been asked before, without a 'clean' answer, but you'll find some options in these questions: http://stackoverflow.com/questions/664896/get-the-vk-int-from-an-arbitrary-char-in-java and http://stackoverflow.com/questions/1248510/convert-string-to-keyevents – AVee Dec 14 '11 at 12:46

4 Answers4

7
char ch='c';
int code = ch;
System.out.println(code);

OUTPUT:

99

just for escape char \ you have to use like char ch='\\';

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • @JonMannerberg It should work with every character, but be carefull with the special ones. `\` should be `\\`(because it is the escaping character and with its help, you can see the keycode of other characters. – Dragos Dec 14 '11 at 12:49
  • just for escape char \ you have to use like char ch='\\'; – dku.rajkumar Dec 14 '11 at 13:02
5
public static int KeyEvent.getExtendedKeyCodeForChar( int key );

This will return an extended key code for the unicode character key.

As stated at here:

Returns: for a unicode character with a corresponding VK_ constant -- this VK_ constant; for a character appearing on the primary level of a known keyboard layout -- a unique integer. If a character does not appear on the primary level of a known keyboard, VK_UNDEFINED is returned.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
Lex Luthor
  • 61
  • 1
  • 2
4

A way is this:

char c = 'f';

System.out.println("code="+(int)c);

I mean, you should make a casting form char to int;

Dragos
  • 2,911
  • 12
  • 39
  • 55
1

System.out.println((int) 'c');

LynAs
  • 6,407
  • 14
  • 48
  • 83