Space pressed bug in Obj-C?
I'm working on an Obj-C app for OSX in which the user presses space (or return) to call a function. However sometimes after the user presses the space bar a couple times the program thinks the user is still pressing space, thus it calls the function thousands of times until crash. I've put a delay in so space can only be pressed once every 2 seconds, however that only slows down the crash. The only way to stop the crash is for the user to press space again.
How can I resolve this?
int key = ([[incomingEvent charactersIgnoringModifiers] UTF8String])[0];
key =开发者_开发问答 [incomingEvent keyCode];
switch(key)
{
// return and space
case 36:
case 49:
if (CFAbsoluteTimeGetCurrent() - lastSpaceTime > acceptableTimeBetweenSpace)
{
// do stuff
printf("space pressed");
// lastSpaceTime is now
lastSpaceTime = CFAbsoluteTimeGetCurrent();
}
else
{
printf("not enough time since last space!");
// break;
// return incomingEvent;
}
break;
case 53:
//do stuff
break;
}
I tried adding this:
CGEventRef simulateSpaceUp, simulateSpaceDown;
simulateSpaceDown = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)49, true);
simulateSpaceUp = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)49, false);
in the else block. What am I doing wrong here?
Seems like recognizing the spacebar key isnt the problem here. It does seem likely that the delay u put in is adjusted to some large amount of time (or negative).
Why arent u using a NSTimer to shutout the spacebar key method? u just set a bool prop (canNotReactToSpaceBar) to true and after timer runs out u set it back to false when the timer has run out. With the bool u just shutout the particular method when the bool is set on true, etc.
精彩评论