How to detect which number key is pressed?


#1

How do I detect which number key is pressed? In my keyPressed() I want to respond to the number keys (main keyboard, not number pad)

Right now I’m doing:

    if (key.getKeyCode() >= '1' &&
        key.getKeyCode() <= '7')
    {
          // stuff
    }
    else if (key.getKeyCode() == '!' ||
             key.getKeyCode() == '@' ||
             key.getKeyCode() == '#' ||
             key.getKeyCode() == '$' ||
             key.getKeyCode() == '%' ||
             key.getKeyCode() == '^' ||
             key.getKeyCode() == '&')
    {
        // other stuff
    }

I’m basically creating a musical keyboard you play with the keyboard. So I don’t really care what key is pressed, more it’s position. The above won’t work for keyboards that aren’t US, since the shift+number key changes. Ay way to get something equivalent to the windows virtual key codes?


#2

Things may have changed in the years since I implemented the keyboard code, but I remember all the OS APIs being a bit of a car-crash in that department, and I don’t think any of them had a good, clean way of finding out the actual keyboard layout or mapping that to keystrokes. It may be possible by baking in your own lookup tables for different regions, but IIRC it seemed like it’d be a nightmare to implement.


#3

We’ve added some code that should do this correctly on Mac but you’ll need to enable carbon support. Apparently, all the keyboard layout code is still carbon under the hoods and there is no good replacement yet. See this code: