Reputation: 21
I am making a simple piano game for Mac. And when user pressed the keyboard,the key of piano
can be pressed simultaneously.
However, I am clueless about how to check when "D,F....." key is pressed on the Mac's keyboard.
Objective-C
Upvotes: 2
Views: 8538
Reputation: 9392
Do you have a NSView subclass as the piano view? If you do, then just override the -(void)keyDown:(NSEvent *)event
method, and record down whatever key you want. For Example:
-(void)keyDown:(NSEvent *)event {
NSString *characters;
characters = [event characters];
switch (characters)
{
case 'd':
//do something;
default:
break;
}
}
Upvotes: 1
Reputation: 27
By using this code you can catch all key press events.
i is KeyCode . sample kVK_End
while (true)
{
for (int i=0; i<128; i++)
{
if (CGEventSourceKeyState(kCGEventSourceStateCombinedSessionState,i))
{
NSLog(@"Key Press");
}
}
}
Upvotes: 0
Reputation: 21373
As with so many things, there are multiple ways to do this. However a simple way is to override -keyDown:
in your NSView subclass. Presumably, this would be the NSView subclass that draws your piano keyboard. Example:
- (void)keyDown:(NSEvent *)event
{
switch ([event keyCode])
{
case 0x02:
// D key pressed
break;
case 0x03:
// F key pressed
break;
// etc.
}
}
I find the Key Codes app handy for finding key codes, but you can also just put a log statement in your -keyDown:
method then press keys to find the corresponding codes. They're also in the <HIToolbox/Events.h>
header.
See Apple's Event Handling Guide for more information.
Upvotes: 2