2
votes

I'm looking to read the state of the keyboard in Cocoa (for a game I'm building in SpriteKit).

NSResponder will certainly give me key presses, but I don't get events for modifier presses, and if I hold down a single key, and then press another key, I stop getting keyDown events for the first.

In ancient times (on my MacPlus), I used GetKeys() to fetch the keyboard state at the top of each frame. I'm surprised and baffled that this still seems to work:

KeyMap keys; 
GetKeys(keys); 
UInt32 keys3 = CFSwapIn32BigToHost(keys[3].bigEndianValue); 
if (keys3 & 4) 
{ 
    NSLog(@"F1 is down"); 
}

However, I'm certain that there must be issues with localization, different keyboards, or something (using a 30-year old toolbox call gives me pause).

Is there a modern equivalent to this function?

1

1 Answers

3
votes

There are a couple of ways you could do this, centering around the NSEvent API.

  1. You could ask the NSApplication instance for the currentEvent. This will give you an NSEvent, and you could inspect its characters, charactersIgnoringModifiers, modifierFlags, etc.
  2. If you're only interested in modifiers, you could just ask for the +[NSEvent modifierFlags] to return to you a bit mask of the currently pressed modifier keys.
  3. You could install an event monitor (either global or local) to notify when you keys and/or modifiers change.

The last approach is probably the best one, because it doesn't require polling.