Mac OS X - Get state of spacebar

血红的双手。 提交于 2020-01-16 00:50:29

问题


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


来源:https://stackoverflow.com/questions/16150267/mac-os-x-get-state-of-spacebar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!