fill the void - bdunagan

22 Feb 2010
Cocoa Tip: NSApp's currentEvent

Let’s say I want to detect a modifier key. This information is embedded in every NSEvent object as flags in the modifierFlags attribute. But what if my current method isn’t passed an event? The answer is not NSApp’s nextEventMatchingMask. I explored that option for too long before moving on. The answer is NSApp’s currentEvent. With it, I have easy access to the current event that the application is dealing with. To detect the modifier keys, I simply extract the modifierFlags attribute and check it for them.

// Detect the modifier flags (keys) from the current NSEvent.
NSEvent *event = [NSApp currentEvent];
if (event != nil) {
	BOOL isCommandKey = ([event modifierFlags] & NSCommandKeyMask) != 0;
	BOOL isShiftKey = ([event modifierFlags] & NSShiftKeyMask) != 0;
Previous LinkedIn Twitter GitHub Email Next