2
votes

I am trying to keep track of the pressed keys. I have glutIgnoreKeyRepeat(1) and I register the key events (down/up for normal and special) in an object that keeps track of the keys pressed (called the list of pressed keys from now on) so that I just check in my display function if a key is pressed by looking in that list.

The problem is with SHIFT: Different keys register as DOWN and UP (depending on whether SHIFT was pressed or not) for the same physical keyboard key (eg. a and A, 1 and !, [ and { etc.)

Consider this (with {key1 key2} representing my list of pressed keys after the event):

  • initial state : {} no keys listed as pressed
  • SHIFT DOWN : {SHIFT}
  • a DOWN : {SHIFT A} (because SHIFT is still down, capital 'A' registers as the key down.
  • SHIFT UP: {A}
  • a UP: {A} (because SHIFT is not pressed, lower 'a' registers as the key up, so a is removed from the pressed key list (which actually doesn't exist), and A still remains)
  • final state: {A} even though no keys are still pressed on the keyboard.

For alpha keys I can solve this by adding/removing the lower case of the keys (a instead of A).

But what about 1 and ! or [ and {. glutGetModifiers doesn't help here. Or what if a key is pressed, the window looses focus, the key is released and the window gains focus again (there is no event to tell that the key was released when the windows lost focus)?

Is there a general solution to check if a key is pressed? (platform dependent solutions are ok, another library is not for me, but maybe for others who need to solve this)

1
Check this solution.Skynet
@Skynet that uses another library or windows api. Doesn't help me, but thanks anyway.bolov
Ok, sorry didn't checkSkynet

1 Answers

1
votes

What you want are the keycodes, the physical number of the key being pressed on the keyboard. These are different on Apple and PC keyboards, and can also be different on keyboards in other countries where the letters change positions.

Most programs don't care about keycodes, they want actual letters and modifier keys, so the system event handler provides a translation from keycode into the intended character/special key. GLUT is designed to be simple, portable, and cross-platform, so uses these routines.

If you're writing a game or simulator, just lowercasing everything is probably good enough. For that kind of high speed interaction, most players won't want to distinguish between 1 and !, or 2 and @. The Ins/Del and arrow key blocks (usually) don't have multiple symbols anyway, and the numeric keypad is too far away for most people to hold down a modifier key at the same time.

If you really, truly, need to track every key state, sorry GLUT won't work for you. On MacOS you ask the NSKeyEvent for the keycode, on MS Windows you use DirectX, on Linux you use the XKeyPress|ReleaseEvent keycode.

Hope this helps.