Let's say you're creating a game for Mac OS X. In fact, let's say you're creating Quake, only it's 2011 and you'd prefer to only use modern, non-deprecated frameworks.
You want your game to be notified when the user presses (or releases) a key, any key, on the keyboard. This includes modifer keys, like shift and control. Edited to add: Also, you want to know if the left or right version of a modifier key was pressed.
You also want your game to have a config screen, where the user can inspect and modify the keyboard config. It should contain things like:
- Move forward: W
- Jump: SPACE
- Fire: LCTRL
What do you do? I've been trying to find a good answer to this for a day or so now, but haven't succeeded.
This is what I've came up with:
- Subclass NSResponder, implement keyUp: and keyDown:, like in this answer. A problem with this approach, is that keyUp: and keyDown: won't get called when the user presses only a modifier key. To work around that, you can implement flagsChanged:, but that feels like a hack.
- Use a Quartz Event Tap. This only works if the app runs as root, or the user has enabled access for assistive devices. Also, modifier key events still do not count as regular key events.
- Use the HIToolbox. There is virtually no mention at all of it in the 10.6 developer docs. It appears to be very, very deprecated.
So, what's the proper way to do this? This really feels like a problem that should have a well-known, well-documented solution. It's not like games are incredibly niche.
-flagsChanged:
orNSFlagsChangedMask
is a hack. It is the documented way of being notified of changes in modifier keys like Control. – user557219-keyDown:
,-keyUp:
,-flagsChanged:
into one or two methods that effectively do the actions in your application — those three methods would simply filter events and call your custom method(s). – user557219if
part, I increment the counter and consider it a key down if the counter is less than 2; otherwise, I decrement the counter and consider it a key up. In theelse
part, I decrement the counter and consider it a key up. I’ve only done this for a single key; you’d have to have a counter for each modifier key. – user557219