捕获NSEvent以添加修饰符问题

时间:2015-06-29 15:35:02

标签: objective-c macos cocoa nsevent

我正在尝试以编程方式在cocoa应用程序中按住我的用户的选项密钥。

对于我的生活,我似乎无法抓住NSEVENT修改它并重新发布它。我仍然想捕获MouseDown事件,因为我使用的位置 - 我一直在尝试抓住事件并向其添加修饰符标志但它似乎不起作用。任何有关这方面的帮助将不胜感激。

这就是我所做的:

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

    if(!(theEvent.modifierFlags == NSAlternateKeyMask)){

        NSEvent *newEvent = [NSEvent keyEventWithType:
                                      theEvent.type
                                      location:theEvent.locationInWindow 
                                      modifierFlags:NSAlternateKeyMask 
                                      timestamp:theEvent.timestamp 
                                      windowNumber:theEvent.windowNumber 
                                      context:theEvent.context 
                                      characters:@"" 
                                     charactersIgnoringModifiers:@"" 
                                     isARepeat:YES 
                                     keyCode:0];
           [super mouseDown:newEvent];
    }   
}

我也尝试过使用CGPostEvent的变体,但它似乎也无法工作。显然只发布一个修饰符标记比看起来更困难。

由于

1 个答案:

答案 0 :(得分:1)

我用这段代码解决了它 -

- (void)mouseDown:(NSEvent *)theEvent {

    if(!(theEvent.modifierFlags == NSAlternateKeyMask)){

        [super mouseDown:[self createNewEvent:theEvent]];
    }
    else {
        [super mouseDown:theEvent];

    }
}

- (NSEvent *)createNewEvent:(NSEvent *)theEvent {
       NSEvent *newEvent = [NSEvent
                         keyEventWithType:NSKeyDown
                         location:theEvent.locationInWindow
                         modifierFlags:NSAlternateKeyMask
                         timestamp:theEvent.timestamp
                         windowNumber:theEvent.windowNumber
                         context:theEvent.context
                         characters:@""
                         charactersIgnoringModifiers:@""
                         isARepeat:NO
                         keyCode:0];
    return newEvent;
}