Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

macos - Mac OS X - Get state of spacebar

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 shorts 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...