I’m trying to detect whether a user quickly presses a keyboard key twice, a double press. The pressing of the key is an NSEvent, and is caught by this method:
- (void)sendEvent:(NSEvent *)theEvent
{
NSString* keysPressed = [theEvent characters];
if ( [keysPressed isEqualToString:@" "] )
{
if(theEvent.type==NSKeyDown)
NSLog(@"spaceDown");
if(theEvent.type==NSKeyUp)
NSLog(@"spaceUp");
}
}
The log statements do in fact appear upon pressing and releasing the space bar, but now I want to detect if the user double taps the space bar, and distinguishing that from two individual presses. I think we’d have to create a custom solution to this.
How can I detect if two space bar key press events were, say, 0.3 seconds apart (thus making it a double press), and then performing a certain action if that condition is met?
At least 2 possible solutions to this.
BOOL doubleKeypress = YES, then kick off anNSTimerwith fire delay0.3to setdoubleKeypress = NO.In both cases you’ll need to make sure you only check against previous presses of that key, so maybe store the
BOOLs or times with an associatedkeyCodefrom theNSEvent.It’s made easier in that you can always overwrite an existing “previous event” since you’re only detecting double keypresses and thus you only ever need to track 1 previous keypress. Make sure to set it to
nilif you do fire a double keypress though (or else you’ll fire 2 double key events in 3 keypresses, etc)!