Best way to detect Enter / Return key in cocoa app?
in my cocoa app I need to validate the enter / return key. for this i use the code below
if ((event.keyCode == 36) || (event.keyCode == 76) || (event.keyCode == 13))
{
// Some code after checking Enter key
}
Can anyone suggest that this is the right way or not? Thanks in Advance :)
+3
source to share
1 answer
Not exactly the correct way - you are misleading keycodes with character codes. As Peter Hawsey points out in his comment, 13 is the keycode for key W.
That is, it if ((event.keyCode == 36) || (event.keyCode == 76))
checks if the key is a Return or Enter key.
If you want to check the code for a character , you can do something like:
NSString *chars = event.charactersIgnoringModifiers;
unichar aChar = [chars characterAtIndex: 0];
if (aChar == 13 || aChar == 3)
... and you get the same effect.
+3
source to share