Question

I'm having a problem with OS X detecting keystrokes. I need to detect a key down AND a key release or key up whenever a keyboard key is pressed. This is fairly straight-forward when intercepting the application's event handling chain with [ NSEvent addLocalMonitorForEventsMatchingMask: handler: ]. That lets you intercept and modify NSEvents for a variety of event types, including NSKeyUp and NSKeyDown for the regular printing keys, as well as NSFlagsChanged which can be used to detect the shift, ctrl, alt, and cmd keys. In fact, because the modifier flags change on both the key up and key down for shift, ctrl, alt, and cmd keys, NSFlagsChanged can be used as a key up and key down event for those keys by checking the [NSEvent modifierFlags] along with the [NSEvent keyCode].

Capslock is different, though. Because the capslock modifier really only acts on a key down, when you press capslock you only get a NSFlagsChanged with capslock is pressed, not when it's released. And NSKeyUp and NSKeyDown aren't emitted with modifier keys like capslock and shift and ctrl, etc.

Can anyone suggest a way, maybe even a lower-level interface, for getting capslock key up events? Am I going to have to resort to using kqueues or something?

Was it helpful?

Solution

IOHIDLib seems to be the only way of doing this. I (or a teammate actually) used IOHIDManager to set up an event callback that successfully intercepted capslock key-up and key-down events.

The awful thing about this is that this is completely outside the Cocoa/CoreFoundation event dispatch mechanism, which means that you get events even when your application is out of focus. You end up having to do a lot of window management and focus detection yourself.

But it does work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top