检测Mac上的空格键事件?

时间:2012-01-15 22:51:11

标签: macos cocoa

我在整个互联网上搜索了一些没有运气的东西。我正在尝试检测用户是否在Mac应用上点击空格键。

-(void)keyDown:(NSEvent*)theEvent;在用户按下字符键时效果很好,但不能输入或空格。

当用户点击回车键或箭头键而不是空格键时,会调用

-(BOOL)performKeyEquivalent:(NSEvent *)theEvent;

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

能够通过子类化NSWindow并实现此方法来实现它:

- (void)sendEvent:(NSEvent *)theEvent
{
    NSString* keysPressed = [theEvent characters];
    if ( [keysPressed isEqualToString:@" "] )
    {
        if(theEvent.type==NSKeyDown)
            NSLog(@"spaceDown");
        if(theEvent.type==NSKeyUp)
            NSLog(@"spaceUp");
    }
}

答案 1 :(得分:0)

根据空格键常量,您可以使用另一个键号为32的循环。

    if ([theArrow length] == 1)
    {
        keyChar = [theArrow characterAtIndex:0];
        NSLog(@"Dentro2 %hu", keyChar);
        switch (keyChar)
        {
            case 32: // Space Bar management

                break;              
        }
    }

    // Manage when any key is dropped.
    if(downOrUp == FALSE)
    {
        NSLog(@"Tecla soltada.");
        self.playerVelocity = CGPointMake(0.0, 0.0);
    }

// Methods to handle key push and key drop
    - (void)keyDown:(NSEvent *)event
    {
        [self handleKeyEvent:event keyDown:YES];
    }

    - (void)keyUp:(NSEvent *)event
    {
        [self handleKeyEvent:event keyDown:NO];
    }

答案 2 :(得分:0)

I stumbled upon it by myself resently. Strangely enough, keyDown: event is detected only by the the method described by moby. But keyUp: works like a charm with space bar press

答案 3 :(得分:0)

在尝试了几个解决方案后,我带来了一个不会为我打破其他事情的解决方案

@import Carbon;

typedef void (^CustomWindowSpacebarKeyCallback)(NSEventType eventType);

@interface CustomWindow : NSWindow

@property (nonatomic, copy) CustomWindowSpacebarKeyCallback spacebarKeyCallback;

@end

@implementation CustomWindow

- (void) sendEvent:(NSEvent *)theEvent
{
   [super sendEvent:theEvent];

   if (([theEvent type] == NSKeyDown || [theEvent type] == NSKeyUp) && _spacebarKeyCallback) {
        NSString *keysPressed = [theEvent characters];
        if ([keysPressed length] == 1) {
            unichar keyChar = [keysPressed characterAtIndex:0];
            if (keyChar == kSpaceCharCode) {
                _spacebarKeyCallback([theEvent type]);
            }
        }
    }
}

@end