Mac OS X - 获取空格键的状态 [英] Mac OS X - Get state of spacebar
问题描述
在 Mac 上,我如何知道键盘上的某个键是按下/向下还是未按下/向上?现在我需要它作为空格键,但适用于任何键的答案将是完美的.
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.
我不想检测事件:
-(void)keyDown:(NSEvent*)event;
-(void)keyUp:(NSEvent*)event;
我想要某个时刻某个键(空格键)的状态.
I want the state of a key (spacebar) at a certain moment.
在 Windows 上,这似乎是可能的(虽然我还没有尝试过),使用以下代码:
On Windows this seems possible (although I haven't tried it out) with the following code:
GetAsyncKeyState(VK_SPACE);
但我还没有找到适用于 Mac 的解决方案.
But I haven't found a solution for Mac yet.
推荐答案
我找到了答案 这里.这是我使用的工作片段:
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
代表你想知道它是否被按下的键.您可以在 Mac 上的以下文件中找到键到 unsigned short
的映射:
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
这篇关于Mac OS X - 获取空格键的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!