问题
How do I know whether a certain key on the keyboard is pressed/down or unpressed/up on Mac? Right now I need it for the spacebar, but an answer that would work for any key would be perfect.
I don't want to detect the events:
-(void)keyDown:(NSEvent*)event;
-(void)keyUp:(NSEvent*)event;
I want the state of a key (spacebar) at a certain moment.
On Windows this seems possible (although I haven't tried it out) with the following code:
GetAsyncKeyState(VK_SPACE);
But I haven't found a solution for Mac yet.
回答1:
I found an answer here. This is the working snippet that I used:
#include <Carbon/Carbon.h>
Boolean isPressed( unsigned short inKeyCode )
{
unsigned char keyMap[16];
GetKeys((BigEndianUInt32*) &keyMap);
return (0 != ((keyMap[ inKeyCode >> 3] >> (inKeyCode & 7)) & 1));
}
inKeyCode
represents the key of which you want to know whether it is pressed or not. A mapping of keys to unsigned short
s can be found in the following file on your Mac:
/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
来源:https://stackoverflow.com/questions/16150267/mac-os-x-get-state-of-spacebar